vue项目和js的知识点

1. 赋值与等号

代码如下(示例):

let a = 5;
let b = 'hello';

2.双引号和单引号的嵌套

当我们在 HTML 模板中使用属性时,避免嵌套冲突的推荐方式是用双引号包裹单引号。
代码如下(示例):

<template>
  <div class="example" :title="'这是一个' + '标题'">
    Vue.js 中的属性赋值方式
  </div>
</template>

3.双向数据绑定时,父组件的 v-model

在使用双向绑定时,父组件也需要使用 v-model,否则数据无法同步到子组件。

  • 父组件:
<template>
  <child-component v-model="value"></child-component>
</template>

<script setup>
import { ref } from 'vue';
const value = ref('');
</script>

  • 子组件:
<template>
  <input v-model="modelValue" />
</template>

<script setup>
const props = defineProps({
  modelValue: String
});

const emit = defineEmits(['update:modelValue']);

watch(() => props.modelValue, (newValue) => {
  emit('update:modelValue', newValue);
});
</script>

4.emit 回调函数

当需要在子组件触发点击事件并传值回去时,通常将 emit 包裹在回调函数中

<template>
  <button @click="handleClick">Click me</button>
</template>

<script setup>
const emit = defineEmits(['customEvent']);

const handleClick = () => {
  emit('customEvent', '传递的值');
};
</script>

5. 遍历循环体中修改数据

<template>
  <ul>
    <li v-for="(item, index) in items" :key="index" @click="toggleActive(index)">
      {{ item.name }} - {{ item.active ? 'Active' : 'Inactive' }}
    </li>
  </ul>
</template>

<script setup>
import { reactive } from 'vue';

const items = reactive([
  { name: 'Item 1', active: false },
  { name: 'Item 2', active: false },
]);

const toggleActive = (index) => {
  items[index].active = !items[index].active;
};
</script>

6. 使用 || 进行默认值赋值

在处理变量赋值时,如果想要防止 undefined 的情况,使用 || 设置默认值。

let value = someVariable || '默认值';

7. 通过按钮控制数据变化

当双向绑定的数据需要通过按钮等操作才能更新时,可以添加一个控制变量来实现。

<template>
  <input v-model="text" />
  <button @click="updateText">更新文本</button>
  <p>{{ displayText }}</p>
</template>

<script setup>
import { ref } from 'vue';

const text = ref('');
const displayText = ref('');

const updateText = () => {
  displayText.value = text.value;
};
</script>

8. 将任何值转换为布尔类型

在 JavaScript 中,可以使用双感叹号 !! 来将任意类型的值转换为布尔类型。

let isTrue = !!someValue;

9. 使用 || 避免 undefined 报错

在判定时,如果值为 undefined,使用 || 来防止报错。

let result = someValue || '默认值';

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值