我想在vue组件中使用jquery函数(最接近)并使用class 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>
答案 0 :(得分:1)
在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上,因此该颜色会自动更新。