<!--
* @Description:
* @Author: pang bo
* @Date: 2021-06-22 14:45:47
* @LastEditTime: 2021-06-22 14:48:29
* @LastEditors: Do not edit
-->
<template>
<input type="text" v-model="listValue" />
<button @click="add">添加</button>
<ul>
<li v-for="(item,index) in list" :key="index">{{ item }}</li>
</ul>
<h1>{{ props.msg }}</h1>
</template>
<script setup>
import { reactive, ref, useContext, watchEffect, watch, onMounted, onUnmounted } from 'vue';
const props = defineProps({
msg: {
typeof: String,
default: "12312"
}
})
const list = reactive([1]);
const listValue = ref('');
const add = () => {
list.push(listValue.value)
listValue.value = ''
}
</script>
<style scoped>
a {
color: #42b983;
}
</style>
修改父组件的值
<template>
<HelloWorld :msg="msg" @changeMsg="changeMsg" />
</template>
<script setup>
import HelloWorld from './components/HelloWorld.vue'
import { ref } from 'vue'
const msg = ref('父组件的值')
const changeMsg = () => {
msg.value = '改变了'
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
子组件
<!--
* @Description:
* @Author: pang bo
* @Date: 2021-06-22 14:45:47
* @LastEditTime: 2021-06-22 14:48:29
* @LastEditors: Do not edit
-->
<template>
<input type="text" v-model="listValue" />
<button @click="add">添加</button>
<ul>
<li v-for="(item,index) in list" :key="index">{{ item }}</li>
</ul>
<div>{{ props.msg }}</div>
<button @click="changeMsg">改变</button>
</template>
<script setup>
import { reactive, ref, useContext, watchEffect, watch, onMounted, onUnmounted } from 'vue';
const props = defineProps({
msg: {
typeof: String,
default: "12312"
},
})
const emit = defineEmit(['changeMsg'])
const list = reactive([1]);
const listValue = ref('');
const add = () => {
list.push(listValue.value)
listValue.value = ''
}
console.log(emit);
const changeMsg = () => {
emit('changeMsg')
}
</script>
<style scoped>
a {
color: #42b983;
}
</style>
效验子组件改变父组件传递的值
const emit = defineEmit({
changeMsg: (value) => {
if (typeof value === 'string') {
return true
}
console.warn('只能传入字符串')
return false;
}
})
const list = reactive([1]);
const listValue = ref('');
const add = () => {
list.push(listValue.value)
listValue.value = ''
}
console.log(emit);
const changeMsg = () => {
emit('changeMsg', 111)
}
文章版权声明:除非注明,否则均为
譬如朝露_策温技术开发工作室博客原创文章,转载或复制请以超链接形式并注明出处。
发表评论
侧栏公告
寄语
譬如朝露博客是一个分享前端知识的网站,联系方式11523518。
热评文章
标签列表
热门文章
友情链接