02-组件
1. vue的组成
<template lang="html">
<!-- 只能存在一个根容器 -->
<div class="">
</div>
</template>
<script>
export default {
name: 'learn',
data() {
return {
}
}
}
</script>
<style lang="css">
</style>
2. 组件创建及引用
<template lang="html">
<div class="">
<!-- 3. 使用组件 -->
<learn/>
</div>
</template>
<script>
// 1. import
import Learn from "./Learn"
export default {
components: {
// 2. 注入
Learn
},
}
</script>
<style lang="css">
</style>
3. 父子传值
- 父传子:
:title="inputData"
=>props: ["title"],
- 子传父:
this.$emit("fromChild", this.inputData)
=>@fromChild="fromChild"
parent.vue
<template>
<div id="app">
<!-- 3. 使用组件
1. 父传子,绑定数据
2. 子传父,事件触发-->
<label>
<input v-model="inputData">
</label>
<learn :title="inputData" @fromChild="fromChild"/>
<p>childData:{{ childData }}</p>
</div>
</template>
<script>
// 1. import
import Learn from "./components/Learn"
export default {
name: 'App',
data() {
return {
inputData: '',
childData: "",
title: {
name: "listao",
age: 28
}
}
},
components: {
// 2. 注入
Learn,
},
methods: {
fromChild(data) {
this.childData = data
}
}
}
</script>
<style>
</style>
child.vue
<template lang="html">
<div class="container">
<p>parentData: {{ title }}</p>
<label>
<input v-model="inputData">
</label>
<button @click="toParent" type="button" name="button">toParent</button>
</div>
</template>
<script>
export default {
// 当前组件名称
name: 'learn',
// 所有的初始化状态全部放入data中
data() {
return {
inputData: ""
}
},
// 接收父组件data
props: ["title"],
methods: {
toParent() {
this.$emit("fromChild", this.inputData)
}
}
}
</script>
<!-- 样式,只有当前组件下生效 -->
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="css" scoped>
.container {
background: red;
}
</style>
4. keep-alive
- 组件之间切换,保持组件状态(失活的组件被缓存)
App.vue
<template>
<div id="app">
<button @click="changeComponent" type="button" name="button">切换组件</button>
<!-- 失活的组件将会被缓存!-->
<keep-alive>
<!-- <component v-bind:is="currentComponent"></component> -->
<component :is="currentComponent"></component>
</keep-alive>
</div>
</template>
<script>
import A from "./components/A"
import B from "./components/B"
export default {
name: 'App',
data() {
return {
currentComponent: A,
flag: false
}
},
components: {
A,
B
},
methods: {
changeComponent() {
if (this.flag) {
this.currentComponent = A
} else {
this.currentComponent = B
}
this.flag = !this.flag
}
}
}
</script>
<style>
</style>
A.vue
<template lang="html">
<div class="">
组件A:{{ msg }}
<button @click="change" type="button" name="button">change</button>
</div>
</template>
<script>
export default {
data(){
return{
msg:"默认"
}
},
methods:{
change(){
this.msg = '改变'
}
}
}
</script>
<style lang="css">
</style>
B.vue
<template lang="html">
<div class="">
组件B
</div>
</template>
<script>
export default {
}
</script>
<style lang="css">
</style>
5. vue文件命名
- 用大驼峰