<script setup lang="ts">
import { onMounted, reactive, toRefs } from "vue";
import List from "./List.vue";
const { chinaTotal, hbData, china, areaTree } = toRefs(data);
const props = defineProps({
distance: Number,
isScroll: Boolean,
endText: {
type: String,
default: "没有更多了",
},
});
const $emits = defineEmits(["getList", "refreshFun"]);
const data = reactive({
scrollEl: null,
startText: "释放即可刷新",
scrollTop: 0,
startY: 0,
translateY: 0,
touchEndTitleShow: false, //控制手指离开屏幕的title显示
touchstartTitleShow: false, //控制手指按下屏幕的title显示
});
let {
scrollEl,
startText,
scrollTop,
touchstartTitleShow,
touchEndTitleShow,
translateY,
} = toRefs(data);
const obj = {
name: '小明',
age: 20,
wife: {
name: '小甜甜',
age: 18,
cars: ['奔驰', '宝马', '奥迪']
}
}
// 把数据变成响应式的数据
// 返回的是一个Proxy的代理对象,被代理的目标对象就是obj对象
// user现在是代理对象,obj是目标对象
// user对象的类型是Proxy
const user = reactive<any>(obj)
console.log(user)
// 通过当前的代理对象把目标对象中的某个数组属性添加一个新的属性
user.wife.cars[3] = '奥拓'
//toRef
const state = reactive({
age: 5,
money: 100
})
// 把响应式数据state对象中的某个属性age变成了ref对象了
const age = toRef(state, 'age')
// 把响应式对象中的某个属性使用ref进行包装,变成了一个ref对象
const money = ref(state.money)
console.log(age)
console.log(money)
const update = () => {
// 更新数据的
// state.age += 2
age.value += 3
// money.value += 10
}
-----------------------------
// action 获取导航数据的方法
const getCategory = async () => {
const res = await getCategoryAPI();
// console.log(res);
CategoryList.value = res.result;
};
</script>
computed
const fullName1 = computed(() => {
return user.firstName + '_' + user.lastName
})
console.log(fullName1)
let infoObj = reactive({
key1: "苹果",
key2: 1000,
});
// 类似vue2的
let newKey = computed(() => {
return infoObj.key1 + ":" + infoObj.key2;
});
// 或者,新增到原有的对象上
infoObj.key3 = computed(() => {
return infoObj.key1 + ":" + infoObj.key2 + "[新增属性的]";
});
------------------
const allPrice = computed(() => {
return cartList.value.reduce((a, c) => a + c.count * c.price, 0)
})
watch
const user = reactive({
firstName: '东方',
lastName: '不败'
})
// 监视 -- 监视指定的数据
// 第三个姓名:
const fullName3 = ref('东方_不败')
watch(
user,
({ firstName, lastName }) => {
fullName3.value = firstName + '_' + lastName
},
{
immediate: true,
deep: true
}
)
// watch---可以监视多个数据的
watch([user.firstName, user.lastName, fullName3], () => {
// 这里的代码就没有执行, fullName3是响应式的数据, 但是, user.firstName、user.lastName不是响应式的数据
console.log('====')
})
// 当我们使用watch监视非响应式的数据的时候,代码需要改一下
watch([() => user.firstName, () => user.lastName, fullName3], () => {
// 这里的代码就没有执行,fullName3是响应式的数据,但是,user.firstName,user.lastName不是响应式的数据
console.log('====')
})
pinia
import { defineStore } from "pinia";
export const useCommodityStore = defineStore("CommodityStore", {
state: () => {
return {
editCommodity: [] as adminListParams,
};
},
actions: {
addCommodityFn(list: adminListParams) {
this.editCommodity = list;
},
},
});
使用watch 侦听props值的变化
<sctipt setup>
import { watch,defineProps } from 'vue';
const props = defineProps({
bool: {
type: Boolean,
required: true
}
})
const props = defineProps({
belong: {
type: String,
required: true,
},
});
//父组件
<Test :name="name"></Test>
watch(
() => props.bool,
(newValue,oldValue) => {
console.log(newValue,oldValue)
}
)
</script>
# vue3-setup语法糖之组件传参(defineProps、defineEmits、defineExpose)
vue3-setup语法糖之组件传参(defineProps、defineEmits、defineExpose) - 掘金 (juejin.cn)
defineProps
父组件:
<template>
<div class="Father">
<p>我是父组件</p>
<!-- -->
<son :ftext="ftext"></son>
</div>
</template>
<script setup>
import {ref} from 'vue'
import Son from './son.vue'
const ftext = ref('我是父组件-text')
</script>
子组件:
<template>
<div class="Son">
<p>我是子组件</p>
<!-- 展示来自父组件的值 -->
<p>接收到的值:{{ftext}}</p>
</div>
</template>
<script setup>
import {ref} from 'vue'
// setup 语法糖写法
//defineProps 来接收组件的传值
const props = defineProps({
ftext: {
type:String
},
})
</script>
defineEmits
子组件:
<template>
<div class="Son">
<p>我是子组件</p>
<button @click="toValue">点击给父组件传值</button>
</div>
</template>
<script setup>
import {ref} from 'vue'
import { ref, defineProps, defineExpose, defineEmits } from 'vue'
// setup 语法糖写法
//用defineEmits()来定义子组件要抛出的方法,语法defineEmits(['要抛出的方法'])
const emit = defineEmits(['exposeData'])
const stext = ref('我是子组件的值-ftext')
const toValue = ()=>{
emit('exposeData',stext)
}
</script>
父组件:
<template>
<div class="Father">
<p>我是父组件</p>
<!-- -->
<son @exposeData="getData" :ftext="ftext"></son>
</div>
</template>
<script setup>
import {ref} from 'vue'
import Son from './son.vue'
const ftext = ref('我是父组件-text')
const getData = (val)=>{
console.log("接收子组件的值",val)
}
</script>
再举例:
import { ref, defineProps, defineExpose, defineEmits } from 'vue'
const emit = defineEmits(['success', 'update'])
f (cart.value) {
emit('success', {
goodsNum: data.value.goodsNum,
skuId,
isCart: true
})
} else {
emit('success', {
goodsNum: data.value.goodsNum,
skuId,
isCart: false
})
}
设置vscode的代码片段
{
"Print to console": {
"prefix" : "v3",
"body": [
"<template>",
" <div>",
" $0",
" </div>",
"</template>",
"",
"<script lang='ts' setup>",
"import { defineComponent,ref,reactive,defineProps,defineEmits,computed,watchEffect } from 'vue'",
"",
"</script>",
"",
"<style lang='less' scoped>",
"",
"</style>",
],
"description" : "Log output to console"
}
}
设置方法:
文件 ---》 首选项 ---》 用户片段 ----》新建全局代码片段-----> 输入名字 vue3 (自定义)------》 粘贴代码片段 ----》回车即可
"prefix" : "vue3", 这里vue3就是我们设置的快捷指令, 可以自己随便更改
export default {
lists: '/892456/17723878'
// getbanner: '其他地址...'
}
import { getLists } from '@/api/index3.js'
//返回一个Promise(发送post请求)
export function axiosPost(url, params) {
return new Promise((resolve, reject) => {
service.post(url, params)
.then(response => {
resolve(response);
}, err => {
reject(err);
})
.catch((error) => {
reject(error)
})
})
}
import { ref, onMounted } from "vue";
import { getBannerAPI } from "@/apis/home";
export function useBanner () {
const bannerList = ref([])
const getBanner = async () => {
const res = await getBannerAPI({
distributionSite: '2'
})
console.log(res)
bannerList.value = res.result
}
onMounted(() => getBanner())
return {
bannerList
}
}
const routes = [
{
path: '/',
name: 'home',
component: HomeView
}
// 路由传递参数
{
path: '/routeView/:id',
name: 'routeView',
component: () => import(/* webpackChunkName: "about" */ '../views/RouteView.vue'),
// 子路由
children: [
{
// http://localhost:8080/routeView/3/moduleOne
path: 'moduleOne', // 注意这里不能写成 path: '/moduleOne'
name: 'moduleOne',
component: () => import('../views/routeModule/ModuleOne.vue')
},
...routeModuleRouter,
...routeModuleInRouter
]
},
{
path: '/axiosView',
name: 'axiosView',
component: () => import(/* webpackChunkName: "about" */ '../views/AxiosView.vue')
},
{
path: '/xssCsrf',
name: 'xssCsrf',
component: () => import(/* webpackChunkName: "about" */ '../views/XssCsrf.vue'),
meta: {
requireAuth: true // 需要登录验证
}
}
]