初学vue2 之 组件

全局组件

1. 在main.js 内注册一个组件

 

// import bottom from '../reusecomponents/bottom.vue'
// Vue.component('bottom ', bottom)
// 注册组件要写在new Vue前面

Vue.component('my-component', {
  template: '<div @click="componentevent()">{{msg}}————{{num}}</div>',
  data () {
    return {
      msg: '全局组件',
      num: 0
    }
  },
  methods: {
    componentevent () {
      this.num++
      console.log(this.aa)
    }
  }
})

2. 在app.vue中使用

<template>
  <div id="app">
    ...
    <my-component></my-component>
  </div>
</template>

 

组件之间 Prop传递数据

父传子

1.在字bottom组件内生命一个数据

<template>
  <div class="bottom">
    <h1>{{message}}</h1>
    ...
  </div>
</template>
<script>
export default {
  ...
  props: ['message']
}
</script>

2.在父组件中传入

<bottom message="传入内容字符串"></bottom> 

这时父组件传入的是一个静态字符串,如果想要传入一个动态数据时可以如下修改父组件

<template>
  <div class="hello">
    ...
    <bottom :message="num"></bottom>  // 用 v-bind 来动态绑定
  </div>
</template>
<script>
import bottom from '../reusecomponents/bottom.vue'
export default {
  ...
  mounted(){
    var _this = this
    setInterval(function(){      // 数据变化
      _this.num++
    },1000)
  },
  data () {
    return {
      num:1     // 要传入的动态数据
    }
  },
  components:{
    bottom,
  }
}
</script>

 

 

 

单文件组件

1. 首先在src下创建一个存放单文件组件的目录reusecomponents,并在此目录下新建bottom.vue

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

<script>
export default {
  name: 'bottom',
  data () {
    return {
      msg: 'bottom模块内容',
    }
  },
}
</script>

<style scoped>
.bottom {
  width: 500px;
  height: 500px;
  background: #cdcdcd;
}
</style>

2. 在想要使用bottom组件的地方引入

<template>
  <div class="hello">
    <bottom></bottom>  // 这里!!!!!!!!!!!!!!!
  </div>
</template>

<script>
import bottom from '../reusecomponents/bottom.vue'  // 这里!!!!!!!!!!!!
export default {
  created(){
      this.fetchData()
  },
  watch:{
      '$route':'fetchData'
  },
  methods:{
      //路由转换
    fetchData(){
    },
  },
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App',
    }
  },
  components:{ 
    bottom,   // 这里!!!!!!!!!!!!!
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值