【Vue3 从入门到实战 进阶式掌握完整知识体系】015-探索组

2021-06-30  本文已影响0人  訾博ZiBo

6、组件间双向绑定高级内容

不能写多个v-model但是可以写多个带属性的v-model:XXX

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>hello vue</title>
  <!-- 引入Vue库 -->
  <script src="https://unpkg.com/vue@next"></script>
</head>

<body>
  <div id="root"></div>
</body>

<script>
  const app = Vue.createApp({
    data(){
      return{
        count: 1,
        count1: 1
      }
    },
    template: `
        <div>
          <test v-model:app="count" v-model:app1="count1" />
        </div>
    `
  });

  
  app.component('test',{
    // modelValue 是固定写法
    props:['app', 'app1'],
    methods:{
      add(){
        // 固定写法
        this.$emit('update:app', this.app + 3)
      },
      add1(){
        // 固定写法
        this.$emit('update:app1', this.app1 + 3)
      }
    },
    template: `
        <div @click="add()">{{app}}</div>
        <div @click="add1()">{{app1}}</div>
    `
  })

  const vm = app.mount('#root');
</script>

</html>

运行结果

image-20210613155739018.png

自定义v-model上的修饰符

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>hello vue</title>
  <!-- 引入Vue库 -->
  <script src="https://unpkg.com/vue@next"></script>
</head>

<body>
  <div id="root"></div>
</body>

<script>
  const app = Vue.createApp({
    data(){
      return{
        count: 'a'
      }
    },
    // 自定义一个修饰符
    template: `
        <div>
          <test v-model.uppercase="count" />
        </div>
    `
  });

  
  app.component('test',{
    // modelValue 是固定写法
    // props:['modelValue'],
    props:{
      'modelValue': String,
      'modelModifiers': {
        default: () => ({}) // 默认为空
      }
    },
    methods:{
      add(){
        let newValue = this.modelValue + 'c';
        if(this.modelModifiers.uppercase){
          newValue = newValue.toUpperCase();
        }
        this.$emit('update:modelValue', newValue);
      }
    },
    template: `
        <div @click="add()">{{modelValue}}</div>
    `
  })

  const vm = app.mount('#root');
</script>

</html>

运行结果

image-20210613161146449.png
上一篇 下一篇

猜你喜欢

热点阅读