Vue组件Prop传递数据

组件实例的作用域是孤立的,这就意味着不能在子组件的模板内直接使用父组件的数据,要让子组件使用父组件的数据,我们需要通过Props选项。

Prop

1、Prop是单向绑定的,也就是说当父属性的值发生变化时,将传递给子组件,但是不会反过来;
2、每次父组件更新时,子组件的所有 prop 都会更新为最新值。

<ul>
    <!-- 在这里使用我们刚才定义的组件 -->
    <todo-item
    v-for="(item,index) of list"
    :key="index"
    //把item的值赋值给component
    :content="item"
    >
</todo-item>
</ul>

我们父组件中属性要想在我们子组件中使用,需要用到prop属性进行传递

  Vue.component('todo-item',{
        // template为我们组件的模板
        props: ['content'],
        template:'<li>{{content}}</li>'
    }

完整联系代码:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>vue入门</title>
  <script src="./vue.js"></script>
</head>
<body>
<div id="root">
    <!--  -->
    <div>
    <input v-model="inputValue"/>
    <button @click="submit">提交</button>
</div>
     <!--循环取出item里面的值 -->
<!-- <ul>
    <li v-for="(item,index) of list" :key="index">
   
        {{item}}
    </li>
</ul> -->
<ul>
    <!-- 在这里使用我们刚才定义的组件 -->
    <todo-item
    v-for="(item,index) of list"
    :key="index"
    :content="item"
    >
</todo-item>
</ul>
</div>

<!-- 在body里面加一个<script>标签我们去创建一个vue的实例 -->

<script>
    // 这里我们去自定义一个组件内容(全局组件)
    Vue.component('todo-item',{
        // template为我们组件的模板
        props: ['content'],
        template:'<li>{{content}}</li>'
    }

    )
    new  Vue({
        el:"#root",//el:大意是我让vue这个实例去接管页面上哪个元素(vue实例去和哪个dom节点做绑定)
        data:{
        show:true,
        inputValue:"",
        list:[]
        },
        methods: {
            submit:function(){
                //当我们按下提交按钮时,要往数据里增加一个数据
                this.list.push(this.inputValue),
                this.inputValue=""
            }
        }

    })   
</script>
</body>
</html>

原文链接:https://www.cnblogs.com/dyfbk/p/6872475.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章