简体   繁体   中英

How to a pass parameter be a variable onclick and vue js

I want to send second parameter like my variable on js, it is a string but i want it to be variable after send it

<button id="txt" onclick="activate(this.id, 'group_question.active')" class="kind-btn"type="button">
  <i class='fas fa-poll-h kind-icon'></i>
</button>
<button id="pic" onclick="activate(this.id, 'group_question.active')" class="kind-btn"type="button"style="padding-left: 15px;">
  <i class='fas fa-image kind-icon'style="font-size: 30px;"></i>
</button>
<button id="sound" onclick="activate(this.id, 'group_question.active')" class="kind-btn"type="button">
  <i class="material-icons kind-icon"style="font-size: 31px;top: 8px;margin-bottom: 13px;">music_video</i>
</button>

//js
function activate(id, rec) {
  let saver = rec.replace(/['"]+/g, ''); // i wanna rec be variable for using it to change style
  console.log(typeof saver);
  if (saver != id) {
    $("#" + saver).css({"background-color": "white", "color": "#fe5d87"});
  }
  saver = id;
  $("#" + saver).css({"background-color": "#fe5d87", "color": "white"});

var group_question = new Vue({
  el: '#cr_que',
  data: {
    active: "txt"
  },

You can't use this.id in your vue template. Also, you don't need jQuery for this and you also should not use it with Vue.js . See: Why not use jQuery with Vue.js for AJAX? .

Instead You can write a method, pass a value, and set the data. Then in your template you apply styles if the value matches :class="type === 'text' && 'selected'" :

 const app = new Vue({ el: '#app', data() { return { type: null } }, methods: { activate(type) { this.type = type; } }, })
 .selected { background-color: #fe5d87; color: white; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/> <div id="app"> <button id="text" @click="activate('text')" class="kind-btn" :class="type === 'text' && 'selected'" type="button"> <i class='fas fa-poll-h kind-icon' style="font-size: 30px;"></i> </button> <button id="pic" @click="activate('pic')" class="kind-btn" :class="type === 'pic' && 'selected'" type="button" style="padding-left: 15px;"> <i class='fas fa-image kind-icon' style="font-size: 30px;"></i> </button> <button id="sound" @click="activate('sound')" class="kind-btn" :class="type === 'sound' && 'selected'" type="button"> <i class="material-icons kind-icon" style="font-size: 31px; top: 8px; margin-bottom: 13px;">music_video</i> </button> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM