組件的使用
比如說將搜索框作為一個可復用的組件
理論知識:
- 父組件可以使用 props 把數據傳給子組件。
- 子組件可以使用 $emit 觸發父組件的自定義事件。
例子:
1.子組件:在components中新建一個.vue文件(最好帶文件夾)
<template>
<view class="search-wrap">
<u-search :placeholder="placeholder" :show-action="false" height="80" @input="handleInput"></u-search>
</view>
</template>
<script>
export default {
name: 'cm-search', //定義一個組件名
props: { //定義屬性,便於修改組件中的變量值
placeholder: {
type: String, //placeholder的類型為字符串。
default: '搜索' //定義一個默認的屬性,可以在使用的時候通過屬性修改搜索框中的內容。
},
},
data() {
return {
};
},
methods: { //定義方法
handleInput(e) { //input時間觸發handleInput方法
//debugger
this.$emit('input2', e) //子組件可以使用 $emit 觸發父組件的自定義(input2)事件
}
}
}
</script>
<style lang="scss">
</style>
2.父組件:
<cm-search @input2="handleInput2"></cm-search>
<!-- 使用定義的子組件,子組件的input觸發父組件的input2事件,然后就能調用handleInput2方法l -->
<script>
import CmSearch from '../../components/search/search.vue' //引入組件vue文件
export default {
components: {CmSearch}, //使用CmSearch組件
data() {
return {
};
},
methods:{
handleInput2(event){ //調用方法
console.log(event)
//debugger
}
}
}
</script>
