Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue3 components

作者:冷言寡语   发布日期:2026-02-05   浏览:47

<template>
  <div>
    <h1>{{ message }}</h1>
    <ChildComponent :count="count" @increment="incrementCount" />
  </div>
</template>

<script>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';

export default {
  name: 'ParentComponent',
  components: {
    ChildComponent
  },
  setup() {
    const message = 'Hello Vue 3!';
    const count = ref(0);

    const incrementCount = () => {
      count.value++;
    };

    return {
      message,
      count,
      incrementCount
    };
  }
};
</script>

<style scoped>
h1 {
  color: #42b983;
}
</style>

解释说明

  1. 模板部分 (<template>):

    • 包含一个 h1 标签,用于显示 message 的值。
    • 使用了 ChildComponent 组件,并通过属性传递 count,同时监听 increment 事件。
  2. 脚本部分 (<script>):

    • 导入了 ref 函数和 ChildComponent 组件。
    • 定义了一个名为 ParentComponent 的组件。
    • setup 函数中定义了响应式变量 messagecount,以及方法 incrementCount
    • 返回这些变量和方法,使其可以在模板中使用。
  3. 样式部分 (<style scoped>):

    • 定义了 h1 标签的颜色为绿色。

子组件示例 (ChildComponent.vue)

<template>
  <button @click="$emit('increment')">Increment ({{ count }})</button>
</template>

<script>
export default {
  name: 'ChildComponent',
  props: {
    count: Number
  }
};
</script>

<style scoped>
button {
  padding: 10px 20px;
  background-color: #42b983;
  color: white;
  border: none;
  cursor: pointer;
}
</style>

解释说明

  1. 模板部分 (<template>):

    • 包含一个按钮,点击时触发 increment 事件,并显示当前的 count 值。
  2. 脚本部分 (<script>):

    • 定义了一个名为 ChildComponent 的组件。
    • 接收一个名为 count 的属性。
    • 使用 $emit 触发父组件的 increment 事件。
  3. 样式部分 (<style scoped>):

    • 定义了按钮的样式。

上一篇:vue :class 动态绑定样式

下一篇:创建一个vue3项目

大家都在看

vue.js devtools用法

three.js vue

vue js for循环

vue.min.js 本地引入

highlight.js vue

vue.config.js 配置

vue.config.js 配置代理

vue.config.js configu

node.js vue

vue3 写法

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站