How to use keys to query values in Json objects in Vuejs 3
P粉413307845
2023-09-02 20:14:08
<p>I'm new to Vuejs and need to access the 'label' via the 'id' reference. </p>
<p><code>const Wizard_steps = ref([ { id: 1, label: "Step 1" }, { id: 2, label: "Step 2" }, { id: 3, label: " Step 3" } ]) const currentstep = ref([number]) </code></p>
<p>If currentstep === 2, I want to access the data of "step 2", I tried:
<code>wizard_steps.filter(id=2).label</code></p>
List highlights here.
You can use
Array::find()
to find a value in an array. Alternatively, you can usecomputed
to get a responsive value for use in templates. Also, I think you can usereactive
instead ofref
to handle the steps. If the step will not change you can removereactive
as it is not needed in this case.Solution
In Vue, we use reactive variables to affect DOM variables. Here we can declare
wizard_steps
which can later be obtained from the.value
key of the object created in the const variable - you can see this in the provided code. We need to create a variable that can operate on the selected ID. Based on the selected ID, we can use a simple JavaScript array and thefind()
function to find the selected step and display its label. Use thecomputed()
function to adjust the label associated with the current step based on responsive changes incurrent_step_id
, which also declares a responsive variable. However, this variable cannot be manipulated directly. Instead, update its.value
when the reactive variable it uses internally changes.You can view this sample code.