初学vue2 之 组件

全局组件

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

// 注册组件要写在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>

猜你喜欢

转载自blog.csdn.net/qq_39785489/article/details/79928154