zoukankan      html  css  js  c++  java
  • vue子组件数据跟着父组件改变

    父组件的代码

    <template>

        <div class="home">

            <img alt="Vue logo" src="../assets/logo.png">

            <!--<HelloWorld msg="Welcome to Your Vue.js App"/>-->

            父组件的值<input type="text" v-model="parentVal">

            <div>

                <child-test :inputData="parentVal"></child-test>

            </div>

        </div>

    </template>

    <script>

        // @ is an alias to /src

        import HelloWorld from '@/components/HelloWorld.vue'

        import ChildTest from '@/components/child-test.vue'

        export default {

            name: 'home',

            components: {

                HelloWorld,ChildTest

            },

            data() {

                return {

                    parentVal: 100,

                }

            },

        }

    </script>

     

    子组件的代码

    <template>

        <div class="child">

            子组件<input type="text" v-model="childVal">

        </div>

    </template>

    <script>

        export default {

            name: 'child',

            props: {

                inputData: {

                }

            },

            data() {

                return {

                    childVal: this.inputData

                }

            },

            watch: {

                inputData(newVal){

                    this.childVal = newVal;

                }

            }

        }

    </script>

     

    总结:父组件通过props传值给子组件,子组件通过watch监听父组件传过来的值改变来重新更新子组件的值。以此来达到子组件的值跟随父组件的值改变。如果不使用watch,虽然父组件传过来的值改变了,但是子组件不会自动更新。

  • 相关阅读:
    【LeetCode】328. 奇偶链表
    【LeetCode】24. 两两交换链表中的节点
    【LeetCode】83. 删除排序链表中的重复元素
    【LeetCode】141. 环形链表
    【LeetCode】02.07. 链表相交
    【LeetCode】876. 链表的中间结点
    【LeetCode】2. 两数相加
    【LeetCode】02.01. 移除重复节点
    【LeetCode】21. 合并两个有序链表
    【LeetCode】剑指 Offer 06. 从尾到头打印链表
  • 原文地址:https://www.cnblogs.com/ranyonsue/p/11940607.html
Copyright © 2011-2022 走看看