Files
2024-09-27 02:06:13 +08:00

117 lines
3.2 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="app">
<!-- 父传子的写法1 -->
<abc :xixi="text"></abc>
<!-- 局部组件的两种写法 -->
<!-- <c></c> -->
<!-- 父传子的写法2 -->
<def></def>
<def :x="'2333 传了参数'"></def>
<!-- 子传父 -->
<def @click="get" :x="'2'"></def>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script>
// 父组件————>子组件 传数据 用!!props!!
// 方法1:在子组件定义一个数组(props:['xx']) > Vue-datd中写一个值(text:'xx') > <xx(子组件标签名) :xx(数组中的名字)="text" > 子组件中template写<h2>{{xx(数组中的名字)}}<h2>
// 方法2:在子组件定义一个对象(props:{xx:{}}) > <xx(子组件名) :xx(props里的xx) > 子组件中template写<h2>{{xx(props里的xx)}}<h2>
// 子组件————>父组件 $emit 借助这个把数据抛出去 $parent
// 全局组件(两个参数 '名字(不能是html默认标签的名字)',值(必须是{}))
Vue.component('abc', {//abc是标签名 可以随便取名
// template就是html标签 必须写
template: `
<div>
<h2>{{title}}</h2>
//父传子的写法1
<h2>{{xixi}}</h2>
</div>
`,
// 写法1
props: ['xixi'],
data() {
return {
title: '我是全局组件',
}
},
created() {
console.log("我是全局组件的生命周期:", this);
},
})
// 局部组件 def是变量名 不是标签名
var def = {
template: `
<div>
<h2>{{title}}</h2>
//父传子的写法2
<h2>{{x}}</h2>
//子传父
<h2 @click="submit">{{x}}</h2>
</div>`,
// 写法2
props: {
x: {
default: "父组件向子组件传数据方法2 没传参数默认写",
type: String
}
},
data() {
return {
title: '我是局部组件',
list: "子传父"
}
},
created() {
console.log("我是局部组件的生命周期:", this);
},
methods: {
submit() {
this.$emit("change", this.list)//两个参数 参数1:自定义名字 参数2:要抛出去的值
}
}
}
new Vue({
el: '.app',
data: {
text: '父组件向子组件传数据 方法1'
},
methods: {
get(val) {
console.log("父组件收到的数据:", val);
}
},
// 局部组件
components: {
// 方法一
//"c": def, //非简写
// 方法二
def //当名字和值一样时(def(标签名):def(变量名))可以简写为(def)
}
})
</script>
</html>