Vue元件間傳值 和 訪問
阿新 • • 發佈:2021-06-24
1、根元件向子元件傳值 :使用props屬性
<html> <body> <script src="vue.js"></script> <template id="myt"> <div> <p>{{name}}</p> <p>{{pwd}}</p> <p>{{cmsg}}</p> </div> </template> <div id="app"> <cpn :person="p" :cmsg="msg"></cpn> </div> <script> Vue.component("cpn", { template: "#myt", props: { person: Person, cmsg: String } })
//定義一個Person物件 function Person(m, p) { name= m; pwd = p; } const app = new Vue({ el: "#app", data: { msg: "hello", p: new Person("張三", 123) }, }) </script> </body> </html>
props可以是陣列形式表示 :props:['prop1','prop2','prop3'] ,也可以物件形式props:{prop1:String,prop2:Array,prop3:Object} 。物件形式更加靈活。
注意:如果子元件變數使用駝峰命名,在元件上寫屬性時把大寫換成小寫並在前面加-號。
2、子元件向父元件傳值:使用this.$emit()
<html> <body> <script src="vue.js"></script> <template id="myt"> <div> <ul> <li v-for="item in clist"> <button v-on:click="cbtnClick(item)">{{item.name}}</button> </li> </ul> </div> </template> <div id="app"> <cpn :clist="list" @clickbutton="childclickbutton"></cpn> <h3>選擇物件:{{curPerson}}</h3> </div> <script> Vue.component("cpn", { template: "#myt", props:['clist'], methods: { cbtnClick(item) { this.$emit("clickbutton",item); } } }) const app = new Vue({ el: "#app", data: { curPerson: {}, list: [ { id: 1, name: '張三' }, { id: 2, name: '李四' }, { id: 3, name: '王五' }, ], }, methods: { childclickbutton(item) { this.curPerson = item; } } }) </script> </body> </html>
3、父訪問子元件的方法:this.$children ,this.$refs(常用)
<html> <body> <script src="vue.js"></script> <template id="myt"> <div> <h2>{{info}}</h2> </div> </template> <div id="app"> <cpn ref="child"></cpn> <button v-on:click="btnclick">訪問</button> <h3>{{result}}</h3> </div> <script> Vue.component("cpn", { template: '#myt', data() { return { info:"我是子元件屬性" } }, methods: { getInfo() { return this.info; } } }) const app = new Vue({ el: "#app", data: { result: "" }, methods: { btnclick() { this.result = this.$refs.child.getInfo(); } } }) </script> </body> </html>
4、子訪問父元件 :this.$parents (父元件) ,this.$root (根元件)
<html> <body> <script src="vue.js"></script> <template id="myt"> <div> <button v-on:click="btnclick">訪問父</button> <h2>{{msg}}</h2> </div> </template> <div id="app"> <cpn></cpn> </div> <script> Vue.component("cpn", { template: '#myt', data() { return { msg:"" } }, methods: { btnclick() { this.msg = this.$root.msg; } } }) const app = new Vue({ el: "#app", data: { msg: "我是父元件中的值" }, }) </script> </body> </html>