时间:2022-08-26 09:12:53 | 栏目:vue | 点击:次
获取组件传值
<div :style="fontstyle"> <div class="rate" @mouseout="mouseOut"> <span @mouseover="mouseOver(num)" v-for="num in 5" :key="num">☆</span> <!-- <span class="hollow" :style="fontWidth"> <span @mouseover="mouseOver(num)" v-for="num in 5" :key="num">★</span> </span> --> <span class="hollow" :style="fontWidth"> <span @click="onRate(num)" @mouseover="mouseOver(num)" v-for="num in 5" :key="num">★</span> </span> </div> </div>
<script setup lang="ts"> import { defineProps, defineEmits, computed, ref } from "vue" // defineProps<{ // 采用ts专有声明,无默认值 // value: Number, // theme?: String // }>() // 采用ts专有声明,有默认值 interface Props { value: number theme: string } const props = withDefaults(defineProps<Props>(), { value: 0, theme: 'blue' }) // 非ts专有声明 // let props = defineProps({ // value: Number, // theme: { // type: String, // default: 'blue' // } // }) let width = ref(props.value) function mouseOver(i: number) { width.value = i } function mouseOut() { width.value = props.value } const fontWidth = computed(() => `width: ${width.value}em;`) const themeObj: { [key: string]: string } = { 'black': '#000', 'white': '#f80', 'red': '#f5222d', 'orange': '#8f0', 'yellow': '#80f', 'green': '#0f6', 'blue': '#08f',} const fontstyle = computed(() => `color: ${themeObj[props.theme]};`) </script>
<style> .rate { position: relative; display: inline-block; } .rate > span.hollow { position: absolute; display: inline-block; top: 0; left: 0; width: 0; overflow: hidden; } </style>
子组件向父组件事件传递<template>
<div :style="fontstyle"> <div class="rate" @mouseout="mouseOut"> <span @mouseover="mouseOver(num)" v-for="num in 5" :key="num">☆</span> <!-- <span class="hollow" :style="fontWidth"> <span @mouseover="mouseOver(num)" v-for="num in 5" :key="num">★</span> </span> --> <span class="hollow" :style="fontWidth"> <span @click="onRate(num)" @mouseover="mouseOver(num)" v-for="num in 5" :key="num">★</span> </span> </div> </div> </template>
<script setup lang="ts"> import { defineProps, defineEmits, computed, ref } from "vue" ***同上代码省略 // 非ts声明 // let emits = defineEmits(['update-rate']) // function onRate(num) { // emits('update-rate', num) // } // 采用ts专有声明, let emits = defineEmits<{(e: 'update-rate', num: number): void}>() function onRate(num: number) { emits('update-rate', num) } </script> <style> // 同上代码 </style>
在Vue2.X的版本下一些标签可以省略化
语法糖是指在不影响功能的情况下 添加某种方法实现同样的效果 从而方便程序开发。
Vue.js v-bind v-on 指令都提供了语法糖 也可以说是缩写 比如 v-bind 可以省略 v-bind,
直接写一个冒号 ":”:
v-bind 可以省略为 xx:xx 如
<a v_bind:href="xx>连接</a> <a :href="xx">连接</a>
v_on 可以用 @来替代 如
<button v-on:click="xx"/> <button @:click="xx"/>