VUE的组件DEMO
生活随笔
收集整理的這篇文章主要介紹了
VUE的组件DEMO
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
組件的基本寫法可以如下:
HTML:
<div id="components-demo"><button-counter self-data="this is my template"></button-counter></div>
JS:
// 定義一個名為 button-counter 的新組件var ComponentA = {//父組件傳遞過來的數(shù)據(jù)props:['selfData'],template: '<button>{{selfData}}</button>'};new Vue({el: '#components-demo',components: {'button-counter': ComponentA}});
更靈活的寫法如下:
HTML:
<!--props:父dom把數(shù)據(jù)傳遞給子DOM組件的屬性--><!--$emit:子組件通過這個關鍵字方法可以調(diào)用父DOM的方法--><!--slot-scope:子組件屬性傳遞到父DOM,使用此關鍵字進行接收后可以展示其中的屬性值--><!--原則:組件和父DMO是單向的,即,父屬性的修改會影響到子屬性,但是子屬性的修改不可以影響父屬性和雙向綁定的定義還有一點差異--><div id="testList"><ul scope="tt"><!--user這樣的自定義數(shù)據(jù)屬性除了使用v-bind以外,還可以簡寫為:user="item"--><test-list-template v-on:getname="ShowName" v-for="item in users" v-bind:user="item" ><!--作用域插槽必須添加template,v2.5版本推薦使用slot-scope,之前的版本使用scope--><!--這里的userinfo就是slot這個插件所傳遞過來的對象,這個對象可以調(diào)用插槽中自定義的屬性的值,例如userinfo.username和userinfo.userid--><template slot="test-list-name" slot-scope="userinfo"><label>ID:{{userinfo.userid}},姓名:{{userinfo.username}},年齡:</label></template></test-list-template></ul></div>
JS:
<script type="text/template" id="test1"><!--這樣的寫法是模板復用的寫法,不需要帶template這樣的標簽套在外面,否則會報錯--><li v-on:click="SendMsg(user)" ><slot name="test-list-name" :userid="user.id" :username="user.name"></slot>{{user.age}}</li>
</script><script>Vue.component('test-list-template', {//user,父組件傳遞來的數(shù)據(jù)props: ['user'],//子組件模板,這個模板又通過子組件定義的方法調(diào)用了父組件的方法template: '#test1',methods: {SendMsg: function (user) {//第一個是父組件的方法名,第二個是傳遞的參數(shù),父組件對應的是v-on:getname,這個getname是父組件的方法名this.$emit('getname', user);}}});new Vue({el: '#testList',data: {users: [{ id: 1, name: '張三', age: 20 },{ id: 2, name: '李四', age: 22 },{ id: 3, name: '王五', age: 27 },{ id: 4, name: '張龍', age: 27 },{ id: 5, name: '趙虎', age: 27 }]},methods: {ShowName: function (data) {//data,來自于父組件alert('this is a ' + data.name);}}});
</script> ?
轉(zhuǎn)載于:https://www.cnblogs.com/llcdbk/p/9548352.html
總結(jié)
以上是生活随笔為你收集整理的VUE的组件DEMO的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 外研社丽声拼读故事会插画是谁画的呢?
- 下一篇: 戴尔笔记本电脑windows7壁纸在电脑