<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="app">
{{message}}
<father id="fa"></father>
<div v-ashow="myColor">用自定义指令实现功能</div>
<br>
<button @click="watchTry">测试watch监听功能</button>
<br>
<li>{{watchData}}</li>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script type="x-template" id="children">
<div>
{{hello}}
<button @click="mythief(hello)">点击试试</button>
</div>
</script>
<script type="x-template" id="father">
<div>
<ul>
<li>{{greeting}}</li>
</ul>
<children :mythief="thief"></children>
</div>
</script>
<script>
//自定义指令
//明确钩子函数
// Vue.directive('ashow', {
// inserted:function(el, bindingaa){
// console.log("ashow被调用了 name:" + bindingaa.name + " value:" + bindingaa.value)
// el.style.color = bindingaa.value
// console.log("将样式颜色设置为" + el.style.color)
// }
// })
//在很多时候,你可能想在 bind 和 update 时触发相同行为,而不关心其它的钩子。因此可以简写:
Vue.directive('ashow', function(el, bindingaa){
console.log("ashow被调用了 name:" + bindingaa.name + " value:" + bindingaa.value)
el.style.color = bindingaa.value
console.log("将样式颜色设置为" + el.style.color)
})
var children = {
//父传子参
//所有的 prop 都使得其父子 prop 之间形成了一个单向下行绑定:
//父级 prop 的更新会向下流动到子组件中,但是反过来则不行。
//这样会防止从子组件意外变更父级组件的状态,从而导致你的应用的数据流向难以理解。
props: ["mythief"],
name: "children",
template: "#children",
data() {
return {
hello: "hello Jinzw"
}
},
methods: {
},
}
var father = {
name: "father",
template: "#father",
data() {
return {
greeting: "father myself"
}
},
methods: {
tellYou(){
console.log(greeting)
},
thief(input){
this.greeting = input
console.log("父组件的greeeting变为: " + this.greeting)
}
},
components:{
children: children
}
}
var app = new Vue({
name: "app",
el: "#app",
components:{
father: father
},
data: {
message: "demo study",
myColor: "blue",
watchData: "初始值",
counter: 1
},
methods:{
watchTry(){
console.log("进入绑定点击按钮的事件处理...")
this.watchData = "new 222" + this.counter
this.counter++
console.log("watchTry测试方法 去改动watchData数据为: " + this.watchData)
}
},
watch:{
watchData:function(newVal, oldVal){
console.log("进入监听触发的函数...")
console.log("原来的数值:" + oldVal + " 现在的数值:" + newVal)
console.log("监听到数据变化的处理: " + this.watchData)
}
}
})
</script>
</body>
</html>
Vue 父子组件、父子传参, 自定义指令和响应式侦听
于 2022-04-25 08:58:48 首次发布
本文通过一个示例展示了Vue.js中自定义指令的使用,以及组件间的通信。包括`v-ashow`指令的创建,用于改变元素样式,以及组件`children`和`father`之间的数据传递。同时,还演示了如何监听数据变化并作出响应。通过点击事件,观察`watch`监听器的工作原理。
摘要由CSDN通过智能技术生成