组件基础(一)

Vue组件封装是为了完成代码的复用,既能复用ui又能复用逻辑

组件定义、父组件向子组件传参【props】、子组件通过自定义事件向父组件传值【$emit】

<template>
  <div>
    <input type="password" v-model="pass" />
    <span>{{ passSafe }}</span>
  </div>
</template>

<script>
export default {
  name: "PasswordSafeComponent",
  // 接收父组件传入的参数
  props: ['defaultPass'],
  // 数据声明,与之前方式有变化
  data: function(){
    return {
      passSafe: '',
      // 将父组件传入参数赋值给子组件自己的变量,避免修改prop影响父组件
      pass: this.defaultPass
    }
  },
  watch: {
    pass(value){
      let len = value.length;
      if(len < 6){
        this.passSafe = '低';
      }else if(len > 10){
        this.passSafe = '高';
      }else{
        this.passSafe = '中';
      }
      // 当pass发生改变的时候
      this.$emit('passChange', this.pass);
    }
  }
}
</script>

<style scoped>

</style>

父组件引用

<template>
  <div class="about">
<!--    <h1>This is an about page</h1>-->
    <table align="center">
      <tr>
        <td>用户名</td>
        <td><input type="text" :value="user.username"></td>
      </tr>
      <tr>
        <td>密码</td>
        <td><password-safe-component :default-pass="user.password" @passChange="user.password = $event"></password-safe-component></td>
      </tr>
      <input type="button" @click="doLogin" value="登陆"/>
    </table>
    <!-- 组件的复用 -->
<!--    <password-safe-component></password-safe-component>-->
<!--    <password-safe-component></password-safe-component>-->
<!--    <password-safe-component></password-safe-component>-->
<!--    <password-safe-component></password-safe-component>-->
<!--    <password-safe-component></password-safe-component>-->
  </div>
</template>
<script>
import PasswordSafeComponent from "@/components/PasswordSafeComponent";

export default {
  name: 'About',
  components: {PasswordSafeComponent},
  comments: {
    PasswordSafeComponent
  },
  data: function(){
    return {
      user: {
        username: 'admin',
        password: '123456'
      },
    }
  },
  methods: {
    doLogin(){
      console.log(this.user);
    }
  }
}
</script>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值