vue2 组件13 组件化开发 watch监听器 组件全局化 props props的default props的type props的required必填项

 在vue中,this就是实例对象 

组件被封装后是独立的,使用后才有父子关系

<template>
  <div>
    <div>
      <input type="text" v-model="username">
      <button @click="changName" class="red">数据</button>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      username: 'admin',

    }
  },
  methods: {
    changName() {
      console.log(this.username);
      this.username
    }
  },
  // 当前页面的监听器
  watch: {
    username(newVal,oldVal){
      console.log(newVal,oldVal);
    },
  },
  // 当前页面的计算属性
  computed: {},
  // 当前页面的过滤器
  filters: {}
}
</script>
<!-- lang="less" 预处理器  scoped不会影响到其他页面-->
<style lang="less" scoped>
.red {
  background: red;
  color: aliceblue;
}
</style>

  组件全局化:

  在main.js中导入

 

 

// 导入需要全局注册的组件
import hello from '@/components/HelloWorld.vue'
Vue.component('MYhello',hello)

  引入:

<MYhello></MYhello>

  

 

 props:

  props的值是只读的

  是自定义组件属性

 

<template>
  <div class="hello">
    值:{{init}}
    <button @click="val" class="red">数据</button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  // props是自定义属性,为当前组件指定初始值
  props: ['init'],
  data() {
    return {
      init:0
    }
  },
  methods: {
    val(){
      this.init += 1
    }
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

  

<template>
  <div>
    <div>
      <MYhello init="9"></MYhello>
    </div>
  </div>
</template>

 

 data的值是可更改的,可读可写的,props的值应该转存data上

  如下列:

<template>
  <div class="hello">
    值:{{count}}
    <button @click="count  += 1" class="red">数据</button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  // props是自定义属性,为当前组件指定初始值
  props: ['init'],
  data() {
    return {
      count:this.init
    }
  },
  methods: {

  },
}
</script>

  default:

  外面没有传递init属性时,默认值生效,优先级比较低
<template>
  <div class="hello">
    值:{{count}}
    <button @click="count  += 1" class="red">数据</button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props:{
    init:{
      // 外面没有传递init属性时,默认值生效,优先级比较低
      default:0,
    }
  },
  data() {
    return {
      count:this.init
    }
  },
  methods: {

  },
}
</script>

  type:

    定义属性值默认值

props:{
    init:{
      // 外面没有传递init属性时,默认值生效,优先级比较低
      default:0,
      type:Number,
    }
  },

  required:

props:{
    init:{
      // 外面没有传递init属性时,默认值生效,优先级比较低
      default:0,
      type:Number,
      //必填校验值
      required:true,
    }
  },
posted @ 2022-11-25 17:08  文采呱呱  阅读(720)  评论(0编辑  收藏  举报