【问题标题】:Using Vueify for components with the runtime-only build in Vue.js在 Vue.js 中使用仅运行时构建的组件使用 Vueify
【发布时间】:2017-02-11 17:10:47
【问题描述】:

我一直致力于使用 Vueify 将 vue.js 组件从 vue 1.0 移植到 Vue 2.0。在Starter resources 中声明:

当你使用 vue-loader 或 vueify 导入 *.vue 文件时,它们的部分会自动编译成渲染函数。因此建议使用带有 *.vue 文件的运行时构建。

但是,情况似乎并非如此。如果我有一个简单的组件,例如:

<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>

并且没有收到任何添加到组件的道具,所以:

    <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>

所以在我看来,您可以渲染一个组件,而无需对其进行任何控制,并且您无法对视图模型做任何进一步的事情,所以我真的应该按照建议使用仅运行时构建?

最后,我使用了 aliasify 的独立构建,一切正常,但我真的很想知道在运行时构建使用 vueify 时我缺少什么.当然,我所描述的行为不是应该发生的,所以我只能假设我在某个地方误解了某些东西。

【问题讨论】:

    标签: javascript vue.js vueify


    【解决方案1】:

    做一些测试,问题出在你的默认渲染函数中:

    render: function(createElement) {
        return createElement(MyComponent)
    }
    

    它覆盖了主要的 Vue 文件的渲染函数并创建了一个基础 MyComponent 将其插入到正文中。

    当我移除渲染函数时,道具触发了。

    jsFiddle 试试看,只需取消对渲染函数的注释即可了解我的意思。

    渲染功能旨在通过允许您拥有更多控制权并利用其他模板选项来替换 html 模板。

    【讨论】:

    • 感谢您的回答。渲染功能似乎确实是问题所在。但是,Vueify Documentation 给出了一个包含渲染函数的示例,并且将其留在 runtime-only build 中会导致错误 Failed to mount component: template or render function not defined. (found in root instance)。当您使用独立版本时,似乎所有这些问题都可以避免。
    • 那是因为在文档中它假设你的基础组件是整个应用程序而不是一个单一的部分,本质上要求你创建一个包装器组件来处理你的应用程序的主要逻辑和组件。
    • 啊,是的,这就是我所缺少的。谢谢!
    • 没问题。祝你的应用好运。
    猜你喜欢
    • 2015-05-02
    • 2016-01-27
    • 2016-04-07
    • 2017-04-10
    • 2016-10-24
    • 2019-07-16
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多