首页 > 解决方案 > 在 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.js

解决方案


在 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来自孩子的事件。在这种情况下,发生的情况是从子级传递的颜色值用于更新父级中的颜色值。

然后,由于父级将.boxdiv 的背景颜色绑定到数据值 color,所以颜色会自动更新。


推荐阅读