vue3父子通信

Posted 老张在线敲代码

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue3父子通信相关的知识,希望对你有一定的参考价值。

组件通信详细请看https://blog.csdn.net/weixin_48927323/article/details/125486312

父组件内


 
<script setup lang="ts">
import  ref, computed  from "vue";
import BlogPost from "./components/BlogPost.vue";
const blogs = ref([
  
    id: 1,
    title: "vue3基础教程",
    content: "vue3在vue2的基础上做了重大改动",
    link: "vue3.org",
  ,
  
    id: 2,
    title: "react基础教程",
    content: "react17.0在react16.0的基础上做了重大改动",
    link: "react.org",
  ,
  
    id: 3,
    title: "javascript基础教程",
    content: "js可以适用于多个框架使用",
    link: "js.org",
  ,
]);
const total = computed(() => blogs.value.length);
const isShow = ref(true);
function showTotal() 
  isShow.value = !isShow.value;


const initBlogForm = 
  title: "",
  content: "",
  link: "",
;
const blogForm = ref(
  ...initBlogForm,
);
function addPost() 
  console.log(blogForm);
  if (blogForm.value.title == "") 
    alert("不允许为空");
    return;
   else 
    blogs.value.push(
      id: blogs.value.length + 1,
      ...blogForm.value,
    );
  
  blogForm.value =  ...initBlogForm ;

</script>
 <template>
  <BlogPost v-for="item in blogs" :key="item.id" v-bind="item"> </BlogPost>
  <div v-if="isShow"> total 篇文章</div>
  <button @click="showTotal"> isShow ? "隐藏" : "显示" 总数</button>
  <!-- 表单数据 -->
  <form @submit.prevent="addPost">
    <label for="blogTitle">博客标题</label>
    <input type="text" id="blogTitle" v-model="blogForm.title" />
    <label for="content"></label>
    <textarea
      id="content"
      cols="30"
      rows="10"
      v-model="blogForm.content"
    ></textarea>
    <input type="text" id="link" v-model="blogForm.link" />
    <button type="submit">提交</button>
  </form>
</template>
<style scoped>
form 
  display: grid;
  margin-top: 20px;

</style>

子组件内

<template>
  <h1>
    <a :href="link"> title </a>
  </h1>
  <article>
    <div> content.slice(0, 100) </div>
    <button v-if="content.length > 100">阅读原文</button>
  </article>
</template>
<script setup lang="ts">
import  defineProps  from "vue";
const props = defineProps(["title", "content", "link"]);
</script>

以上是关于vue3父子通信的主要内容,如果未能解决你的问题,请参考以下文章

Vue3父子组件间传参通信

vue3 非父子组件通信

Vue3 父子组件通信

VUE3+TS(父子兄弟组件通信)

Vue3 组件通信学习笔记

Vue3父子组件通讯一目了然