VUE-组件基础

1.基本示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<div id="app8">
    <button-counter></button-counter>
</div>
<script>
    Vue.component('button-counter',{
        data:function(){
            return{
                count:0
            }
        },
        template:'<button v-on:click="count++">你点击我{{count}} 次</button>'
    });
    new Vue({el:"#app8"})
</script>

  

2.组件可复用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<div id="app8">
    <button-counter></button-counter>
    <button-counter></button-counter>
    <button-counter></button-counter>
</div>
<script>
    Vue.component('button-counter',{
        data:function(){
            return{
                count:0
            }
        },
        template:'<button v-on:click="count++">你点击我{{count}} 次</button>'
    })
    new Vue({el:"#app8"})
</script>

注意当点击按钮时,每个组件都会各自独立维护它的 count。因为你每用一次组件,就会有一个它的新实例被创建。  

 

3.data必须是一个函数

当我们定义这个 <button-counter> 组件时,你可能会发现它的 data 并不是像这样直接提供一个对象:

1
2
3
data: {
  count: 0
}

取而代之的是,一个组件的 data 选项必须是一个函数,因此每个实例可以维护一份被返回对象的独立的拷贝:

1
2
3
4
5
data: function () {
  return {
    count: 0
  }
}

如果 Vue 没有这条规则,点击一个按钮就可能会像如下代码一样影响到其它所有实例  

4.通过Prop向子组件传递参数

1
2
3
4
5
6
7
8
9
10
11
12
<div id="app8">
    <blog-post title="My journey with Vue" name="1"></blog-post>
    <blog-post title="Blogging with Vue" name="2"></blog-post>
    <blog-post title="Why Vue is so fun" name="3"></blog-post>
</div>
<script>
    Vue.component('blog-post',{
        props:['title','name'],
        template:'<h3>{{title}}<b>{{name}}</b></h3>'
    })
    new Vue({el:"#app8"})
</script><br><br>输出:

     My journey with Vue1

     Blogging with Vue2

     Why Vue is so fun3

  

posted @   MiniDuck  阅读(182)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2017-10-19 表单form-input标签禁止聚焦输入
点击右上角即可分享
微信分享提示