html:
<div id="app">
<mytemplace></mytemplace>
</div>
javascript:
<script>
const { createApp } = Vue
const app = createApp({})
app
.component('mytemplace', {
template: '<div><button>返回</button></div>'
})
.mount('#app')
</script>
结果展示:
html:
<div id="app">
<mytemplate></mytemplate>
</div>
javascript:
<script>
const { createApp, ref } = Vue
const app = createApp({})
app
.component('mytemplate', {
template:
'<div> <input type="text" v-model="inputText" /><childTemplate @click="buttonClk"></childTemplate><ul><li v-for="item in myDataList">{{ item }}</li></ul></div>',
data() {
return {
myDataList: ['123', '123qwe', 'aaa'],
inputText: ''
}
},
methods: {
buttonClk() {
console.log('自定义组件-父组件点击事件')
}
},
components: {
childTemplate: {
template: '<button @click="childButtonClk">点击</button>',
methods: {
childButtonClk() {
console.log('自定义组件-子组件点击事件')
}
}
}
}
})
.mount('#app')
</script>
1.结果展示:
2.点击按钮输出结果:
父传子通过属性向下传递:在子组件中自定义属性名,并传递相应的参数过去。子组件通过 props 接受传过来的参数
<body>
<div id="app">
<mytemplace mypros="传递固定参数"></mytemplace>
<mytemplace :mypros="parentProps"></mytemplace>
<mytemplace :mypros="parentProps" :mypros1="parentProps1"></mytemplace>
</div>
<script src="./lib/vue.global.js"></script>
<script>
const { createApp } = Vue
const app = createApp({
data() {
return {
parentProps: '传递动态参数属性前加冒号',
parentProps1: true
}
}
})
app
.component('mytemplace', {
template: '<div><button>{{mypros+"-"+mypros1}}</button></div>',
//属性校验,指定参数类型
props: {
mypros: String,
mypros1: Boolean
}
// props: ['mypros', 'mypros1']
})
.mount('#app')
</script>
</body>
子传父通过事件传递参数:子组件的点击事件通过 this.$emit(父组件中自定义的事件名称, 传递的参数) 传递参数到父组件;父组件通过自定义事件接收参数
<body>
<div id="app">
<mytemplace @myevent="parentClick($event)"></mytemplace>
</div>
<script src="./lib/vue.global.js"></script>
<script>
const { createApp } = Vue
const app = createApp({
methods: {
parentClick(e) {
console.log('父组件点击:' + e)
}
}
})
app
.component('mytemplace', {
data() {
return { childProp: '子组件属性' }
},
template: '<div><button @click="childClick()">返回</button></div>',
methods: {
childClick() {
this.$emit('myevent', this.childProp)
}
}
})
.mount('#app')
</script>
</body>
子组件(标签)中定义 ref 属性后,可以通过 this.$refs.ref属性名 获得子组件(标签)对象,从而获取子组件(标签)的控制权
<body>
<div id="app">
<!-- 通过ref获取输入框的内容 -->
<input type="text" ref="myInputText" />
<mytemplace ref="myRef"></mytemplace>
<button @click="parentClick">父组件点击事件</button>
</div>
<script src="./lib/vue.global.js"></script>
<script>
const { createApp } = Vue
const app = createApp({
data() {
return { parentPro: 'refTest' }
},
methods: {
parentClick() {
this.$refs.myRef.childClick(this.parentPro)
}
}
})
app
.component('mytemplace', {
data() {
return { childProp: '子组件属性' }
},
template: '<div><button @click="childClick()">返回</button></div>',
methods: {
childClick(e) {
console.log('子组件点击事件', e)
}
}
})
.mount('#app')
</script>
</body>