Vue手动创建子组件实例,是否设置父组件会影响子实例设置道具值

时间:2018-10-16 10:54:24

标签: vue.js vuejs2

  1. 代码:

// Child Component
var TestComp = Vue.component('TestComp', {
    template: `<div>Child Component Prop Value : {{text}} </div>`,
    // child component prop --> text
    props: {
        text: {
            default: 'init prop'
        }
    }
});


// Parent
var vm = window.vm = new Vue({
    el: "#root",
    template: "#app",
    mounted() {
        this.createSubComp();
    },
    data() {return {}},
    methods: {
        createSubComp() {
            var that = this;
            var copy = Vue.extend(TestComp);
            var instance = window.vmsub = new copy({
                // here, remove comment
                // parent: that
            });
            // add or remove comment above, cause different result 
            instance.text = 'pass child component prop';
            instance.$mount();
            this.$el.append(instance.$el);
        }
    },
    components: {
        TestComp
    }
});
<script src="https://vuejs.org/js/vue.min.js"></script>

<div id="root"></div>

<script type="text/x-template" id="app">
  <div style="height: 100; border: 1px solid red; overflow: auto;">
  </div>
</script>

  1. 子组件:TestComp,它具有名为'text'的prop属性,
    父组件的名为“ createSubComp”的方法正在尝试创建子组件实例

    当像现在这样注释“ parent:that”时,“ instance.text ='xx”将执行成功,并且不引发任何异常。

    但是当我删除'parent:that comment'时,'instance.text ='xx'会引发异常:
    避免直接更改prop,因为每当父组件重新渲染时,该值都会被覆盖,
    而是使用基于属性值的数据或计算属性。道具被更改:“文字”

    我想添加代码“ parent:that”,以便子实例可以在vue-devtools中显示。 我想知道添加/删除评论时会导致不同结果的原因。

    英语不好...谢谢...

1 个答案:

答案 0 :(得分:0)

我认为您使用Vue组件的方法看起来像一些变通办法,可以实现非常特殊的功能...

但是,如果不是这种情况,则更简单的Vue实现方法看起来更像这样,只需让Vue.js进行其构建即可:

// Child Component
var TestComp = Vue.component('TestComp', {
    template: `<div>Child Component Prop Value : {{text}} </div>`,
    // child component prop --> text
    props: {
        text: {
            default: 'init prop'
        }
    }
});


// Parent
var vm = window.vm = new Vue({
    el: "#root",
    template: '<test-comp text="pass child component props" />', // passing props to child component, using template
    data() {return {}},
    components: {
        TestComp
    }
});
<script src="https://vuejs.org/js/vue.min.js"></script>

<div id="root"></div>

<script type="text/x-template" id="app">
  <div style="height: 100; border: 1px solid red; overflow: auto;">
  </div>
</script>

Vue.js将为您创建子组件