VueCompilerError: v-model cannot be used on v-for or v-slot scope variables because they are not writable. Why?
<template>
<div v-for="service in services" :key="service.id">
<ServicesItem v-model="service"></ServicesItem >
</div>
</template>
<script lang="ts">
import ServicesItem from "#js/components/ServicesItem.vue"
export default defineComponent({
components: { ServicesItem },
setup() {
const services = ref([
{
id: 1,
name: "Service 1",
active: false,
types_cars: {
cars: {},
suv: {},
},
},
])
return {
services,
}
},
})
</script>
What are the best practices? Reactive object transfers
Okay, so what's going on is that the variable "service" is, let's say, virtual.
It doesn't exist, it's just a part of your real object "services" at a certain point (iteration).
If you'd like to "attach" that iteration to your component, you need to provide a real object, and in your case that would be done like that:
<div v-for="(service, i) in services" :key="service.id">
<ServicesItem v-model="services[i]"></ServicesItem >
</div>
Same issue here, i've change the modelValue props by an other custom props, and it works fine for me.
old:
const props = defineProps({
modelValue: {
type: Object,
required: true
}
})
NEW:
const props = defineProps({
field: {
type: Object,
required: true
}
})
Component:
<MyComponent :field="service"/>
instead of
<MyComponent :v-model="service"/>
Related
I'm using react-router v 6.4 with createBrowserRouter to support the new data API.
I have routes that have a loader, and this loader can take 1-2 sec to get the data from the server, and I want to show a loading animation at that time.
See the following as a simple example of what I have, and a comment pointing to what I was expecting to do/find in the docs:
const router = createBrowserRouter([
{
path: '/',
element: <Layout/>,
children: [
{
index: true,
element: <Screen title="Home"/>,
},
{
path: 'materials',
loader: async () => {
return (await fetch('/api/materials')).json()
},
fallbackElement: <Loading />, // <<--- THIS IS WHAT I WAS EXPECTING TO DO
element: <Materials/>,
},
{
path: 'projects',
loader: async () => {
return (await fetch('/api/projects')).json()
},
element: <Projects/>,
},
],
},
])
Could not find how to place a "fallback" element on a route to show while the loader is waiting for the data, only to place a fallbackElement on the RouterProvider component, but that is not what I want (it shows the fallback element only on the mount of RouterProvider, not when changing between routes).
Seems kinda weird that such a thing is not supported, and cannot really find answers through the search here as well.
As per the documentation, on the component consuming the loader data you have to use React.Suspense and Await components to show the fallback, something like this:
import { Await, useLoaderData } from "react-router-dom";
function Book() {
const { book, reviews } = useLoaderData();
return (
<div>
<h1>{book.title}</h1>
<p>{book.description}</p>
<React.Suspense fallback={<ReviewsSkeleton />}>
<Await
resolve={reviews}
errorElement={
<div>Could not load reviews 😬</div>
}
children={(resolvedReviews) => (
<Reviews items={resolvedReviews} />
)}
/>
</React.Suspense>
</div>
);
}
https://reactrouter.com/en/main/components/await#await
That's in theory, because I've done that and my loaders are not showing either.
I am trying to build dynamic content from a SharePoint list using SPFX. I'd like to use jQuery to build an accordion view of the data. The issue is that I can't even seem to get the element once the page is rendered.
In my code I am requiring a file called ota.js with the following code:
console.log('Start');
function otaExpand(){
console.log('otaExpand Function Called');
let spListContainer = document.getElementById('spListContainer');
console.log(spListContainer);
}
window.addEventListener("load", otaExpand());
In my ts file this is my render method:
public render(): void {
this.domElement.innerHTML = `
<div>
<div id="spListContainer">TEST</div>
</div>
`;
//this._renderListAsync();
//($('.accordion', this.domElement) as any).accordion();
}
When I review the console, I get my messages, but the element itself comes back as null.
console.log
I am using SharePoint 2019 on premise with the following configuration.
+-- #microsoft/generator-sharepoint#1.10.0
+-- gulp-cli#2.3.0
`-- yo#2.0.6
node --version
v8.17.0
I should also mention I am using TypeScript with no JavaScript framework.
Does anyone know why I can't access this element from my js file?
Thanks!
My overall goal is to call list data and apply an accordion style to it (https://jqueryui.com/accordion), but I can't even get passed capturing the element to change it.
I've tried calling my code from a js file as well as trying to put the code directly in the html. Neither worked.
OK, I finally figured out what I was doing wrong. I was calling my jQuery in the render() method rather than in _renderList where this.domElement actually makes sense.
Here's my code in case anyone wants to avoid the pain I put myself through. This allows you to specify a list in the site and you just need to add the fields you want to display.
import { Version } from '#microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneChoiceGroupOption,
IPropertyPaneConfiguration,
PropertyPaneChoiceGroup,
PropertyPaneCustomField,
PropertyPaneTextField
} from '#microsoft/sp-webpart-base';
import { escape } from '#microsoft/sp-lodash-subset';
import styles from './GetSpListItemsWebPart.module.scss';
import * as strings from 'GetSpListItemsWebPartStrings';
import {
SPHttpClient,
SPHttpClientResponse
} from '#microsoft/sp-http';
import * as jQuery from 'jquery';
import 'jqueryui';
import { SPComponentLoader } from '#microsoft/sp-loader';
import PropertyPane from '#microsoft/sp-webpart-base/lib/propertyPane/propertyPane/PropertyPane';
export interface IGetSpListItemsWebPartProps {
title: string;
description: string;
listField: string;
}
export interface ISPLists {
value: ISPList[];
}
export interface ISPList {
ID: string;
Title: string;
Website: {
Description : string,
Url : string
};
Description : string;
}
export default class GetSpListItemsWebPart extends BaseClientSideWebPart<IGetSpListItemsWebPartProps> {
private _getListData(): Promise<ISPLists> {
return this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl + "/_api/web/lists/GetByTitle('" + this.properties.listField + "')/Items",SPHttpClient.configurations.v1)
.then((response: SPHttpClientResponse) => {
return response.json();
});
}
private _renderListAsync(): void {
this._getListData()
.then((response) => {
this._renderList(response.value);
})
.catch(() => {});
}
private _renderList(items: ISPList[]): void {
let listData = `
<h1>${this.properties.title}</h1>
<h2>${this.properties.description}</h2>
<div class="accordion">
`;
items.forEach((item: ISPList) => {
let Description : string;
item.Description ? Description = item.Description : Description = "";
listData += `
<h3> ${item.Title}</h3>
<div>
<table>
<tr>
<td>OTA URL</td>
<td>${item.Website.Description}</td>
</tr>
<tr>
<td>Description</td>
<td>${Description}</td>
</tr>
</table>
</div>
`;
});
listData += '</div>';
this.domElement.innerHTML = listData;
const accordionOptions: JQueryUI.AccordionOptions = {
animate: true,
collapsible: true,
icons: {
header: 'ui-icon-circle-arrow-e',
activeHeader: 'ui-icon-circle-arrow-s'
}
};
jQuery('.accordion', this.domElement).accordion(accordionOptions);
}
public render(): void {
this._renderListAsync();
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneTextField('title',{
label: strings.TitleFieldLabel
}),
PropertyPaneTextField('description', {
label: strings.DescriptionFieldLabel
}),
PropertyPaneTextField('listField', {
label: strings.ListFieldLabel
})
]
}
]
}
]
};
}
public constructor() {
super();
SPComponentLoader.loadCss('//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css');
}
}
Your code from the "ota.js" file is probably called before your HTML is initialized (i.e. before the "render()" function is executed). To make sure this is the case, you could add log to the "render()" function to see when it's called.
In other words, "window.load" event happens long before "render()" function is called. This is how web parts are loaded - dynamically after full load of the page. Or "window.load" does not happen at all - web parts may be loaded by the user when using the page designer, i.e. without page reload.
To fix the issue, you should get the element after it's created, i.e. after the "render()" function creates the element you are trying to get.
After updating a series of dependencies, most notably jest and react/react-dom, a once working Unit Test is no longer working. After spending the last week reading through the ChangeLogs of the dependencies that changed, I still cannot find out why it is breaking.
The Component - stripped down for the relevant portions
[imports, etc.] ->not code, just giving a stripped down version
class MyComponent extends React.Component {
render() {
const { Foo, errorNotice, disabled } = this.props;
return (
<form autoComplete="Off">
<Paper className="top-paper edit-form">
<h1>{ Foo.id ? 'Edit' : 'Add' } My Foo </h1>
<div className="flex">
<div className="flex-column">
<FormControl
className="has-columns"
component="fieldset"
>
<TextField
id="foo-name"
fullWidth={true}
disabled={disabled}
name="name"
inputProps={{ maxLength: 50 }}
className="block"
label="Name"
value={Foo.name}
onChange={this.props.onChange}
error={!!errorText.name}
helperText={errorText.name}
/>
[closing tags, etc.] -> as as above, not code, just giving a stripped down version
export default MyComponent
The Test
import React from 'react';
import { shallow } from 'enzyme';
import MyComponent from "./my-component";
const Foo = {
name: 'Foo Name',
val_x: 'NONE'
};
const handleTextChange = jest.fn(({ target: { name, value} }) => {
Foo[name] = value;
testMyComponent.setProps({ Foo });
});
const testMyComponent = shallow(
<MyComponent
Foo={Foo}
errorNotice={{}}
onChange={handleTextChange}
/>
);
describe('Test component display', () => {
it('Name field show display attachment point name', () => {
const nameInput = testMyComponent.find('[name="name"]');
expect(nameInput.props().value).toBe(Foo.name);
});
});
^^ This Test Passes
describe('Test Foo interactions', () => {
it('Updating Name field should update Foo name', () => {
const newName= 'New Name';
testMyComponent.find('[name="name"]').simulate('change', {
target: { name: "name", value: newName }
});
expect(testMyComponent.find('[name="name"]').props().value).toBe(newName);
});
});
^^ This Test Fails on the 'expect' line. The name remains the old name, 'Foo Name'
The output when I call testMyComponent.debug() after the .simulate('change' is as follows (again stripped down)
<WithStyles(ForwardRef(TextField)) id="foo-name" fullWidth={true} disabled={[undefined]} name="name" inputProps={{...}} className="block" label="Name" value="Foo Name" onChange={[Function: mockConstructor] { _isMockFunction: true, ... , results: [ Object [Object: null prototype] {type: 'return', value: undefined } ], lastCall: [ { target: { name: 'name', value: 'New Name' ....
^^ So I can see through lastCall that the handleTextChange function is being called, but its not actually performing the update. Moreover, if I put a test for
expect(handleTextChange).toHaveBeenCalledTimes(1);
Then that text passes, it effectively gets called. But again, the update doesn't actually occur.
The dependencies that were changed were
react 16.13.1 -> 17.0.2
react-dom 16.13.1 -> 17.0.2
jest 24.9.0 -> 27.5.1
material-ui/core 4.11.0 -> 4.12.13
but enzyme stayed the same a 3.11.0
Does any of this make any sense? Like I mentioned I've read changelogs and update posts on all of the dependencies that were updated and I cant see anything that needs to change in the test, but clearly it is failing. I have read Jest/Enzyme Shallow testing RFC - not firing jest.fn() but the solution there is not working for me. I should also mention I have called .update() on the component but to no avail.
Using vue v2.5 with vueCLI 3 trying to have a v-data-table that on each row have a button, when this button clicked should make it appear as loading.
v-btn has loading property by default, really I don't know why is not working...
<v-data-table
:headers="headers"
:items="records"
#dblclick:row="editRowCron_jobs">
<template v-slot:[`item.actions`]="props">
<v-btn color="blue-grey" :loading="props.item.createloading" fab dark small #click="ManuralRun(props.item)">
<v-icon dark>mdi-google-play</v-icon>
</v-btn>
</template>
</v-data-table>
On the click method, I can read but not set the item
export default {
data() {
return {
headers: [
{ text: "id", value: "id", align: " d-none" },
{ text: "actions", value: "actions" }
],
records: [] //grid rows filled by API
}
},
methods: {
ManuralRun(item){
this.records[2].createloading=true; //even I set it like that, nothing happens
item.createloading = true; //property changed here - ok
console.log(item); //here outputs the clicked item - ok
},
so, according to this
the property MUST pre-exist in the array, that means, when we get the result from the API, we have to add the property as:
this.records = data.data.map(record => {
return {
createloading: false,
...record
}
})
I am new to vue.js and currently I am building an app for learning purposes.
What I want to do:
I have a parent component which has a bunch of buttons with different id's.
The child component will wait for those id's to be sent by the parent and it will decide what to display based on the id. Thats all.
I wont post the full code because it's too large but I have tried a bunch of stuff like props and state but honestly it is so confusing.
I come from React background and I am still confused.
Parent component
<template>
<button id="btn1">Show banana</button>
<button id="btn2">Show orange</button>
</template>
<script>
export default {
name: 'Parent',
data: function {
//something
},
props: {
// ?????
}
};
</script>
**Child component**
<template>
<p v-html="something.text">
</template>
<script>
export default {
name: 'Child',
data: function() {
something: ''
if(id from parent === id I want) {
something = object.withpropIneed
}
},
};
</script>
You need to map the data from parent and pass it to child, thats it!
In example i make passing a html string and binding that html received through 'fromParentHtml' prop mapped on child, so inside child component 'this.fromParentHtml' pass to exists because it is defined in props and every time you click in parent button executes the 'show' function and change the value from passed prop to child through parent 'html' data .. =)
<template>
<div>
Current html sent to child '{{html}}'
<br>
<button #click="show('banana')">Banana</button>
<button #click="show('orange')">Orange</button>
<button #click="show('apple')">Apple</button>
<!-- Create child component -->
<child-component :fromParentHtml="html"></child-component>
</div>
</template>
<script>
export default {
name: "test3",
components: {
'child-component': {
template: "<div>Child component... <br> <span v-html='fromParentHtml'></span> </div>",
//Child component map a prop to receive the sent html from parent through the attribute :fromParentHtml ...
props: {
fromParentHtml: {
required: true,
type: String
}
}
}
},
data(){
return {
html: ''
}
},
methods: {
show(fruit){
this.html = '<span>The fruit is ' + fruit + ' !</span>';
}
}
}
</script>
<style scoped>
</style>
If helped you please mark as correct answer! Hope it helps.
Edit 1:
Assuming you have webpack to work with single file components, to import another component just do:
<template>
<div>
<my-child-component></my-child-component>
</div>
</template>
<script>
//Import some component from a .vue file
import ChildComponent from "./ChildComponent.vue";
export default {
components: {
//And pass it to your component components data, identified by 'my-child-component' in the template tag, just it.
'my-child-component': ChildComponent
},
data(){
},
methods: {
}
}
</script>
Just for the sake of it, I think you were looking for this:
<template>
<button id="btn1" #click = "id = 1">Show banana</button>
<button id="btn2" #click = "id = 2">Show orange</button>
<child-component :childid = "id"></child-component>
</template>
<script>
import childComponent from 'childComponent'
export default {
name: 'Parent',
data () {
return {
id: 0
}
},
components: {
childComponent
}
};
</script>
**Child component**
<template>
<p v-html="something.text">
</template>
<script>
export default {
name: 'Child',
props: {
childid: String
},
data: function() {
something: ''
if(this.childid === whatever) {
something = object.withpropIneed
}
},
};
</script>
Solved my problem by taking a different approach.
I have implemented state and my component behaves exactly as I wanted to.
I found this link to be helpful for me and solved my problem.
Thank you.