Vue组件父子传值

159 阅读1分钟

父传子 通过v-bind绑定props的值

 <div id="div1">
        <div>
            <!-- 父组件 -->
            <!-- 通过v-bind绑定props的值 -->
            <child :clist="list" @xg="xg"/>
        </div>
        <template id="child">
            <div>
                <ul>
                    <!-- 子组件 -->
                    <!-- for循环父组件传过来的值渲染到页面上 -->
                    <h1 v-for="(item,index) in clist" :key="index" @click="xiugai(index)">{{item.name}}</h1>
                </ul>
            </div>
        </template>
    </div>

子改父

  • ①使用Vue里面的$emit方法发送一个自定义事件childchange
  • ②在组件上使用@childchange="ctrl" 绑定自定义事件 触发父组件的ctrl方法
  • ③在父组件中的ctrl方法内把父组件的msg的值给改了
 <div id="div1">
        <div>
            <!-- 父组件 -->
            <!-- 通过v-bind绑定props的值 -->
            <child :clist="list" @xg="xg"/>
        </div>
        <template id="child">
            <div>
                <ul>
                    <!-- 子组件 -->
                    <!-- for循环父组件传过来的值渲染到页面上 -->
                    <h1 v-for="(item,index) in clist" :key="index" @click="xiugai(index)">{{item.name}}</h1>
                </ul>
            </div>
        </template>
    </div>
    <script src="./vue.js"></script>
    <script>
        new Vue({
            el: '#div1',
            data: {
                list: [{ name: "张三" }, { name: "李四" }, { name: "王五" },]
            },
            methods: {
                xg(index) {
                    this.list.splice(index, 1)
                }
            },
            components: {
                child: {
                    props: ['clist'],
                    template: "#child",
                    methods: {
                        xiugai(index) {
                            this.$emit('xg',index)
                        }
                    },
                },
            }
        })

$set()方法

 <div id="app">
        <h1>{{list}}</h1>
        <button @click="fn">添加age</button>
        <hr>
        <h1>{{arr}}</h1>
        <button @click="fn2">添加car</button>
    </div>
    <script src="./vue.min.js"></script>
    <script>
        new Vue({
            el:"#app",
            data:{
                list:{
                    name:'tom'
                },
                arr:[{
                    name:'jack'
                },{
                    name:'taotao'
                }]
            },
            methods:{
                fn(){
                    /* Vue2的一个缺陷不可以给对象添加新属性 
                    解决这个bug的方案是 使用$set*/
                    /* this.$set(目标对象,具体的key要使用引号,具体的值) */
                    this.$set(this.list,'age',30)
                    console.log(this.list)
                },
                fn2(){
                    /* 这是更新对象数据的方式 */
                    // this.$set(this.arr[1],'car','bmw')
                    /* 这个更新数组的到视图的方式 */
                    /* 三个参数分别对应 目标数组 数组所在的索引 和需要修改的内容 */
                    this.$set(this.arr,1,{name:'taotao',car:'benchi'})
                }
            }

        })