
如何快速入門VUE3.0:進入學習
此文的背景源自於面試中,被問到, vue和react元件假如需要互通和復用,如何優雅的實現?
除了,開發者手動轉代碼外。目前,我能想到的就2種解決方案
方案一:vue程式碼和react程式碼互轉(元件庫同步)
方案二:直接讓vue元件在React專案中運行,反之也可以。
先看實現效果

vue元件在reat中正常渲染了,而且我還點擊了按鈕3下, vue的回應和render也都正常
實作原理
引入vue的完整版(考慮效能的話,可以按需引入)
等到componentDidMount階段,掛載好<div id="vueApp" />後
在new Vue(..).$mount('#vueApp')
import Vue from 'vue/dist/vue.min.js' // 引入完整版,否則不能解析vue的元件物件語法export default class App extends Component {
constructor(props) {
super(props)
}
componentDidMount() {
const Foo = {
template: `
<div>
<h1>我是vue : {{aaa}}</h1>
<h1>我是vue : {{aaa}}</h1>
<h1>我是vue : {{aaa}}</h1>
<button @click="aaa++">按鈕</button>
</div>
`,
data () {
return {
aaa: 2222
}
}
}
new Vue({
render: h => h(Foo),
}).$mount('#vueApp')
}
render() {
return (
<div>
<h1>目前是react專案內</h1>
<h1>目前是react專案內</h1>
以下將渲染vue元件<div id="vueApp" />
</div>
)
}
}注意:
如果只要支援vue的元件選項物件的話,那就不用配置webpack,就完了
vue的元件選項物件指的是:
const Foo = {
template: `
<div>
<h1>我是vue : {{aaa}}</h1>
<h1>我是vue : {{aaa}}</h1>
<h1>我是vue : {{aaa}}</h1>
<button @click="aaa++">按鈕</button>
</div>
`,
data () {
return {
aaa: 2222
}
}
}此處高級版指的是:需要支援.vue檔案/元件(上面的demo,直接是元件選項對象,沒有.vue檔)
例如:(繼續用上面的demo,改幾行)
import Foo from "./Foo.vue";import Vue from 'vue/dist/vue.min.js' // 引入完整版,否則不能解析vue的元件物件語法import Foo from "./ Foo.vue";
export default class App extends Component {
……
componentDidMount() {
new Vue({
render: h => h(Foo),
}).$mount('#vueApp')
}
……
}此時要生效,需要設定vue-loader
// 在webpack.config.js 內const { VueLoaderPlugin } = require('vue -loader')
module.exports = {
mode: 'development',
module: {
rules: [
{
test: /.vue$/,
loader: 'vue-loader'
}
]
},
plugins: [
// make sure to include the plugin for the magic
new VueLoaderPlugin()
]
}注意點
建議大家test的時候,不要用react的腳手架起的項目,用從零配置webpack.config.js的react項目
我目前用最新版的腳手架時,run eject後,去往webpack.config.js裡面寫會報錯,因為VueLoaderPlugin 不相容一個oneOf的語法
如果不用解析.vue檔的話,直接用vue的元件選項物件語法的話,那麼不用額外的設定vue-loader
建議大家test的時候,不要用react的腳手架起的項目,用從零配置webpack.config.js的react項目
如果不用解析.vue文件的話,直接用vue的組件選項對象語法的話,那麼不用額外的配置vue-loader
最終在對比一下,vue項目中使用react元件,和, react專案中使用vue元件,配置上的差異!
| 一定需要設定webpack.config.js的loader嗎? | |
|---|---|
| 在vue專案中使用react元件 | yes ,需設定babel-loader ,編譯.jsx文件,需要額外注意配babel-loader的option選項 |
| 在react專案中使用vue元件 | no ,如果不用解析.vue檔案的話,直接用vue的元件選項物件語法的話,那麼不用額外的配置vue-loader 。需要支援.vue檔的話,需要配vue-loader |
本文轉載自:https://juejin.cn/post/7083303446161391623
作者:bigtree