赞
踩
目录
原题:
https://github.com/webfansplz/vuejs-challenges/blob/main/questions/25-useMouse/README.zh-CN.md
答案:
- <script setup>
- import { onMounted, onUnmounted, ref } from 'vue'
- function useEventListener(target, event, callback) {
- onMounted(() => {
- target.addEventListener(event, callback)
- })
- onUnmounted(() => {
- target.removeEventListener(event, callback)
- })
- }
- function useMouse() {
- let x = ref(0)
- let y = ref(0)
- useEventListener(window, 'mousemove', e => {
- x.value = e.x
- y.value = e.y
- })
- return {
- x,
- y
- }
- }
- const { x, y } = useMouse()
- </script>
-
- <template>
- Mouse position is at: {{ x }}, {{ y }}
- </template>
Vue
单文件组件设置全局CSS样式原题:
答案:
全局选择器:
如果想让其中一个样式规则应用到全局,比起另外创建一个
<style>
,可以使用:global
伪类来实现。
- <template>
-
- <p>Hello Vue.js</p>
-
- </template>
-
- <style scoped>
- p {
- font-size: 20px;
- color: red;
- text-align: center;
- line-height: 50px;
- }
-
- /* 使其工作 */
- :global(body) {
- width: 100vw;
- height: 100vh;
- background-color: burlywood !important;
- }
- </style>
文档:
原题:
使用 h
渲染函数来实现一个组件。注意: 确保参数被正确传递、事件被正常触发和插槽内容正常渲染
答案:
实现①:
- <script setup>
- import { h } from 'vue'
- import { ElButton } from 'element-plus'
-
- const onClick = () => {
- console.log('onClick')
- console.log(
- Array.from({ length: 20 }).map(() => {
- return h('p', 'hi')
- })
- )
- }
-
- const MyButton = (props, { slots }) => {
- return h(
- ElButton,
- {
- disabled: props.disabled,
- onClick: props.onCustomClick
- },
- slots.default
- )
- }
- </script>
-
- <template>
- <MyButton :disabled="false" @custom-click="onClick">my button</MyButton>
- </template>
实现②:
- MyButton.vue组件:
- <script>
- import { defineComponent, h } from 'vue'
- import { ElButton } from 'element-plus'
-
- export default defineComponent({
- name: 'MyButton',
- emits: ['custom-click'],
- render() {
- return h(
- ElButton,
- {
- disabled: this.$props.disabled,
- onClick: e => {
- this.$emit('custom-click', e)
- }
- },
- this.$slots.default
- )
- }
- })
- </script>
-
- 父组件:
- <script setup>
- import { h } from 'vue'
- import MyButton from './MyButton'
-
- const onClick = () => {
- console.log('onClick')
- console.log(
- Array.from({ length: 20 }).map(() => {
- return h('p', 'hi')
- })
- )
- }
- </script>
-
- <template>
- <MyButton :disabled="false" @custom-click="onClick">my button</MyButton>
- </template>
文档:
Vue3 + Vue-cli (1) 基础篇_vue3 vue-cli_小草莓蹦蹦跳的博客-CSDN博客
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。