Halo
发布于 2022-09-27 / 97 阅读 / 0 评论 / 0 点赞

vue常用属性

props

作用

子组件定义变量, 父组件向子组件传递此变量的值

// son.vue
<template>
    <div>{{numb}}</div>
</template>
<script lang="ts" setup>
    import {defineProps} from 'vue';
    defineProps({
        numb:{
            type:Number,
            default:NaN
        }
    })
</script>
// parent.vue
<template>
    <son @click="func" :numb="numb" />
</template>
<script lang="ts" setup>
    import {ref} from 'vue';
    import son from "./son.vue";
    const numb = ref(0);
    let func = ()=>{
        numb.value++;
    }
</script>

slot

作用

子组件定义位置, 父组件向子组件传递此位置的内容

// son.vue
<template>
    <div>
        <button class="btn-primary">
            <slot>default</slot>
        </button>
    </div>
</template>

<script setup lang="ts">
  
</script>

<style lang="scss" scoped>
.btn-primary{
    padding: 5px 10px;
    background: aquamarine;
    color: #fff;
    border: none;
}
</style>
// parent.vue
<template>
  <son>
  <div>
    <v-button></v-button>
    <br>
    <v-button>确定</v-button>
    <br>
    <v-button>{{msg}}</v-button>
  </div>
  </son>
</template>

<script setup lang="ts">
import son from "./son.vue";
import { ref } from "vue";
const msg = ref("123")
</script>

emits

作用

子组件定义事件, 父组件响应子组件事件

// son.vue
<script setup lang="ts">
import { defineEmits } from 'vue'

const emit = defineEmits(["alertSome"])
function clickButton(){
    //todo
    emit("alertSome",6666)
}
</script>
<template>
    <div>
        <button @click="clickButton">点击我</button>
    </div>
</template>

// parent.vue
<script setup lang="ts">
import son from './son.vue';
function alertSome(data) {
  console.log(data);
}
</script>
<template>
    <div>
        <son @alertSome="alertSome" />
    </div>
</template>

reactive variable

reactive variable 即反应变量, 变量的值改变后, 会重新刷新绑定该变量的组件.
reactive variable 包含 ref/reactive

ref

es 类型数据都可以定义为ref 变量

定义和使用

<script>
const count = ref(0)
count === 0 // false
count.value === 0 // true
</script>

<template>
<div>
<h1>{{ count.value }}</h1> <!--incorrect-->
<h1>{{ count }}</h1> <!--correct-->
</div>
</template>

reactive

reactive 变量是字典性变量

定义和使用

<script>
const data = reactive({
  count: 0,
  name: 'Peter Griffin',
  flag: false
})
</script>

<template>
<div>
<h1>{{ data.name }}</h1> <!--Peter Griffin-->
</div>
</template>

评论