发布时间:2023-10-18 14:00
<template>
<div>
<h1>{{childData}}h1>
<Child @myevent="changeData" :msg="message">Child>
div>
template>
<script>
// 父级向子级传递数据:使用属性传递
import Child from "./components/Child"
export default {
components:{Child},
data() {
return {
message:"app.vue data",
childData:""
}
},
methods:{
changeData(childData){
this.childData = childData
}
}
}
script>
<style>
style>
Child.vue
代码如下
<template >
<div>
<h1>你好啊{{msg}}h1>
<button @click="sendData">传递数据button>
div>
template>
<script>
// 子级向父级传递数据:使用属性传递
export default{
props:["msg"], //得到父级传过来的数据
data() {
return {
childData:"I'm child"
}
},
methods:{
sendData(){
// #emit会找到父级自定义的事件
this.$emit("myevent",this.childData)
}
}
}
script>
app.vue
文件
<template>
<div>
<Carts>Carts>
div>
template>
<script>
//app里面一般不会写数据
import Carts from "./components/Carts.vue" //.vue写不写都可以
//carts购物车
export default {
components:{Carts},
}
script>
<style>
style>
Carts.vue
文件
<template>
<div>
<h1>购物车h1>
<ul>
<li v-for="(v,i) of fruits" :key="i">
{{v.name}}
单价:{{v.price}}
<Counter
:qu="v.qu"
:index="i"
@add="add"
@sub="sub"
>Counter>
li>
ul>
div>
template>
<script>
import Counter from "./Counter"
export default {
components:{Counter},
data() {
return {
fruits:[
{name:"苹果",price:3.14,qu:0},
{name:"香蕉",price:2.14,qu:0},
{name:"梨子",price:1.23,qu:0}
]
}
},
methods:{
add(index){
this.fruits[index].qu++
},
sub(index){
if(this.fruits[index].qu>0){
this.fruits[index].qu--
}
}
}
}
script>
Counter.vue
文件
<template>
<span>
<button @click="sub">-button>
<span>{{qu}}span>
<button @click="add">+button>
span>
template>
<script>
export default {
props:["qu","index"],
methods:{
sub(){
this.$emit("sub",this.index)
},
add(){
this.$emit("add",this.index)
}
}
}
script>
<template>
<div>
<Bother>Bother>
<Sister>Sister>
div>
template>
<script>
import Bother from "./components/Bother"
import Sister from "./components/Sister"
export default {
components:{Bother,Sister}
}
script>
<style>
style>
bother.vue
<template>
<div>
<h1>bother <button @click="changeData">改变数据button>h1>
<p>{{state.message}}p>
div>
template>
<script>
import store from "../store"
export default {
data(){
return{
state:store.state
}
},
methods:{
changeData(){
store.setStateMessage("bother data")
}
}
}
script>
Sisiter.vue
<template>
<div>
<h1>sisterh1>
<p>{{state.message}}p>
div>
template>
<script>
import store from "../store"
export default {
data(){
return{
state:store.state
}
}
}
script>
关闭语法检查