Vue基础语法

 

 

 

组件的创建和定义

定义html之后,在data,之后定义方法,然后在另一个页面里引用,首先在js里引入这个组件,然后在components里声明这个组件,然后在template里引入这个组件.

这个是定义的组件
<template>
  <div >
        <button @click="increment">+</button>
        <button v-on:click="decrement">-</button>
        <p><span>{{num}}</span></p>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      num:0
    }
  },
  methods:{
    increment(){
      this.num++;
    },
    decrement(){
      this.num--;
    }

  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

这个是组件的引用

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
<Counter></Counter>
  </div>
</template>

<script>
import Counter from './Counter'
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  components:{
      Counter
  }
}
</script>

如何从父组件里把数值传输到子组件里呢(也就是传递一个默认值)

在父组件里,引用的组件里设置变量num=10,然后在子组件里用

props:["num"],来传递num这个数

.如何动态的传递数值呢

需要在引用的组件里用v-bind:来动态绑定num这个数,

另外在父组件里显示增加的数值.

 <Counter v-bind:num="num"></Counter>
<p>parentnum:{{num}}</p>
data () {

  return {
    num:10,这个是从父组件向子组件传递的默认值
    msg: 'Welcome to Your Vue.js App'
  }
},

如何每单击一步就让子组件里增加后的数字回显到父组件里呢?

需要在子组件里用$emit来触发点击事件,而且还要再父组件里声明点击事件,事件内容要父组件里写

<Counter v-bind:num="num" v-on:incre="increment" v-on:decre="decrement"></Counter>
<p>parentnum:{{num}}</p>
methods:{
  increment(){
  this.num++;
  },
  decrement(){
  this.num--;
  }
}

在子组件里

methods:{
  increment(){
    this.$emit("incre");
  },
  decrement(){
   this.$emit("decre");
  }

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值