我一直致力于使用 Vueify 将 vue.js 组件从 vue 1.0 移植到 Vue 2.0。在 Starter resources它指出:
When you use vue-loader or vueify to import *.vue files, their parts are automatically compiled into render functions. It is therefore recommended to use the runtime-only build with *.vue files.
然而,事实似乎并非如此。如果我有一个简单的组件,例如:
<template>
<div>
{{ msg }}
</div>
</template>
<script type="text/javascript">
export default {
props: {
msg: {
default: "Child Message"
}
}
}
</script>
在我的 main.js 文件中我这样做:
import Vue from 'vue'
import MyComponent from './my-component.vue';
Vue.component('my-component', MyComponent);
new Vue({
el: '#app',
render: function(createElement) {
return createElement(MyComponent)
}
});
然后使用 Gulp 进行编译:
browserify('./main.js')
.transform(vueify)
.bundle()
.pipe(fs.createWriteStream("bundle.js"))
除了渲染组件之外,我根本无法对组件执行任何操作。事实上,一旦找到 id 为“app”的 div,它就会真正渲染组件:
<div id="app">
<!-- my-component renders even though I didn't ask it to -->
</div>
并且不会收到添加到组件的任何 Prop ,因此:
<div id="app">
<!--
Message displays as default "Child Message" rather than "Parent Message". The prop wasn't passed
-->
<my-component msg="Parent Message"></my-component>
</div>
同样,如果我将 data
添加到 main.js
,则无法从网页访问它:
import Vue from 'vue'
import MyComponent from './my-component.vue';
Vue.component('my-component', MyComponent);
new Vue({
el: '#app',
render: function(createElement) {
return createElement(MyComponent)
},
data() {
return {
msg: "Parent Message"
}
}
});
在 HTML 中:
<div id="app">
{{ msg }} // This will not print
</div>
“#app”内的任何内容根本不会呈现(记住“my-component”即使我不添加它也会呈现):
<div id="app">
<!-- This doesn't render-->
<strong>A component </strong>
<my-component></my-component>
</div>
所以在我看来,你可以渲染一个组件,而无需对其进行任何控制,并且你无法对 View 模型做任何进一步的事情,所以我真的应该按照建议使用仅运行时构建吗?
最后我使用了独立构建 aliasify一切都工作正常,但我真的很想知道在运行时构建中使用 vueify 时我缺少什么。当然,我所描述的行为不是应该发生的,所以我只能假设我在某个地方误解了某些东西。
最佳答案
进行一些测试,问题出在您的默认渲染函数中:
render: function(createElement) {
return createElement(MyComponent)
}
它覆盖主 Vue 文件的渲染函数并创建一个基础 MyComponent,将其插入到正文中。
当我删除渲染函数时, Prop 会被触发。
jsFiddle尝试一下,只需取消注释渲染函数即可明白我的意思。
渲染函数旨在取代 html 模板,让您拥有更多控制权并利用其他模板选项。
关于javascript - 将 Vueify 用于在 Vue.js 中仅运行时构建的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39836988/