vue.js - 在 vue 方法中使用 jquery 函数
问题描述
我想在 vue 组件中使用 jquery 函数(最近)并使用 mainBox 类获取祖先但不起作用并且错误我 this.closest 不是函数
对不起,我是 vue 的新手
这是我的 SubmitPhoneForm 组件:
<template>
<div>
<div class="formBox">
<form>
<input type="tel" placeholder="insert phone"/>
<input type="button" name="next" class="next action-button" value="Next" @click="changecolor()" />
</form>
</div>
</div>
</template>
<script>
export default {
methods: {
changecolor () {
this.closest('.mainBox').css({'background': 'black'})
}
}
}
</script>
这是我在其中使用名为 SubmitPhoneForm 的组件的组件:
<template>
<div>
<div class="mainBox">
<div class="screenBox">
<div class="contentBox">
<div class="title">title</div>
<div class="description">description</div>
<div class="moreDescription"></div>
<submit-phone-form></submit-phone-form>
</div>
<div class="carBox"></div>
</div>
</div>
</div>
</template>
解决方案
在 Vue 中,您真正想做的是从子级发出一个事件,并在父级中监听该事件并让父级管理颜色变化。
这是一个实际应用的小例子。
console.clear()
Vue.component("color-picker", {
template: `<button @click="changeColor">Change color</button>`,
methods:{
changeColor(){
// this random color picker is straight from
// https://www.paulirish.com/2009/random-hex-color-code-snippets/
// Essentially, what you want to do here is tell the parent
// that something has changed in the child and the parent should
// react accordingly.
this.$emit('change-color', `#${Math.floor(Math.random()*16777215).toString(16)}`)
}
}
})
new Vue({
el: "#app",
data:{
color: "#f9f9f9"
},
})
.container {
width: 300px;
margin: auto;
display: flex;
flex-direction: column;
}
.box {
margin: 3em 0;
height: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div id="app">
<div class="container">
<div class="box" :style="{backgroundColor: color}"></div>
<color-picker @change-color="color = $event"></color-picker>
</div>
</div>
在子组件中,发出一个事件。
this.$emit('change-color', <some optional value>)
在父母中,听那个事件。
<color-picker @change-color="color = $event"></color-picker>
这@change-color="..."
是设置一个事件处理程序来监听change-color
来自孩子的事件。在这种情况下,发生的情况是从子级传递的颜色值用于更新父级中的颜色值。
然后,由于父级将.box
div 的背景颜色绑定到数据值 color,所以颜色会自动更新。
推荐阅读
- visual-studio-2015 - 64 位 windows 10 pro visual studio 和 oracle 64 位 - oracle 不是 64 位的错误
- c - 在 C 中初始化 const 变量
- swift - 如何在完成处理程序中使用返回值?
- reactjs - 如何在 Gatsby 2.0 中使用 styled-components 主题
- c# - 计算方法不读取输入
- angular - MS Graph Explorer - 列出加入的团队 - 错误 404
- python - Sqlalchemy 如何查询 citext 数组
- audio - 从 MP4 创建 M4A 文件
- python-3.x - 与数组组合时列表索引超出范围?
- javascript - 如何检查数组中的每个元素的特定条件