title: Vue學(xué)習(xí)一
date: 2019-04-09 21:44:42
tags:
Vue縮寫語法:
v-bind縮寫
<!-- 完整語法 -->
<a v-bind:href="url">...</a>
<!-- 縮寫 -->
<a :href="url">...</a>
v-on縮寫
<!-- 完整語法 -->
<a v-on:click="doSomething">...</a>
<!-- 縮寫 -->
<a @click="doSomething">...</a>
Vue組件的使用
組件是vue.js中最核心的功能,是整個框架設(shè)計最精彩的地方,也是最理解的。
組件的用法
組件與創(chuàng)建vue類似,需要組測之后才能使用。
全局注冊
Vue.component('my-component',{
template:"<h1>這是全局組件</h1>",
})
渲染后結(jié)果
<div id="app">
<h1>這是全局組件</h1>
</div>
父子之間通信
在組件中使用props聲明需要從父級接受的數(shù)據(jù),props的值可以是兩種:字符串或者對象。
<div id="app">
<introduce :titles="msg"></introduce>
<hr>
<for-component :items="lessons"></for-component>
<my-component></my-component>
</div>
<script>
//父向子通信
const introduce = {
template:"<h1>{{titles}}</h1>",
props:['titles']
};
const forComponent ={
template:"<ul><li v-for='item in items'>{{item}}</li></ul>" ,
// props:['items']
props: {items:{
type:Array,
default:['java']
}}
};
const app = new Vue({
el:"#app",
data:{
msg:"大家好",
lessons:["java",'php','python']
},
components:{
introduce,forComponent
}
})
</script>
渲染后的結(jié)果

父子通信結(jié)果
子向父之間通信
子組件用$emit()來觸發(fā)事件,示例代碼如下:
<div id="app">
<counter :num="count" @incr="add" @decr="reduce"></counter>
</div>
<script>
const counter = {
template:`
<div>
<button @click="handleAdd">+</button>
<button @click="handleReduce">-</button>
<h1>Num:{{num}}</h1>
</div>`,
props:['num'],
methods: {
handleAdd(){
this.$emit('incr');
},
handleReduce(){
this.$emit('decr');
}
}
};
const app = new Vue({
el:"#app",
data:{
count:0,
},
components:{
counter
},
methods:{
add(){
this.count++;
},
reduce(){
this.count--;
}
}
})
</script>
const 是ec6中的語法,子向父通信較為麻煩。
渲染后的結(jié)果:

父子通信結(jié)果